Sunday, 2 April 2017

findOneAndUpdate remove element from array if there otherwise put it in there

Is it possible to write a findOne and update that removes element from an array if it is there but if it is not there add it.

I have a useful and notUseful array in "reviews" collection. When the user clicks on the useful button once, I want the userId to be added to the useful array and when he clicks on it again it should be taken off. Also I want to make sure that if he clicks the useful button and he is in the notUseful array we pull him from the notUseful array. that is why you see me do a pull below.

The below only adds the userId once when I click the button multiple times but I would like a findOneAndUpdate to add and remove the id on button click.

function updateArray(){
    var userID = req.user._id ? req.user._id : req.session.anon._id;
    if(req.body.type = "useful"){
        return Review.findOneAndUpdate({_id : req.body.id}, {$addToSet : {useful : userID}, $pull : {notUseful : userID}}, {new : true})
    }


}
updateArray()
    .then(reviewDoc =>{
        console.log("reviewDoc", reviewDoc)
    })
    .catch(err => {console.log(err)})

I was wondering if there was an easy way to do it with findOneAndUpdate

Maybe there is some conditional query magic I use to do this in one shot.



via jack blank

No comments:

Post a Comment