Prasanth Bendra
Prasanth Bendra

Reputation: 32810

How can I assign a operator to variable

I am working on like and unlike section of an image. When a user likes an image, it pushes the userID to an array in mongodb. When a user unlikes an image, it removes the userID from the array. I am trying to do it using $addToSet and $pull.

Question: How can I do it in a single block instead of writing two separate bolcks for these two? Currently I am using a variable opr but it is not working. How can I make it work?

if(likeAction == "like"){
    var opr          = '$addToSet'
}
else if(likeAction == "unlike"){
    var opr          = '$pull'
}

Like.update( 
    { imageID: imageID }, 
    { opr : { userIDs: userID } },
    function(err){
        if(!err){
            Like.findOne({imageID : imageID}, function(err,like){
                image.likeCount      = like.userIDs.length
                image.save(function(err){
                    if(!err){
                        return res.send({
                            status: {
                                error: 0,
                                message: "Successful"
                            }
                        })
                    }
                })
            })
        }
    }
);

Upvotes: 0

Views: 56

Answers (2)

Anthonny
Anthonny

Reputation: 1591

You can do something like that :

var opr, updateCommande = {};

if(likeAction == "like"){
    opr          = '$addToSet'
}
else if(likeAction == "unlike"){
    opr          = '$pull'
}

updateCommande[opr]= { userIDs: userID }

Like.update( 
    { imageID: imageID }, 
    updateCommande,
    function(err){
        if(!err){
            Like.findOne({imageID : imageID}, function(err,like){
                image.likeCount      = like.userIDs.length
                image.save(function(err){
                    if(!err){
                        return res.send({
                            status: {
                                error: 0,
                                message: "Successful"
                            }
                        })
                    }
                })
            })
        }
    }
);

Upvotes: 0

robertklep
robertklep

Reputation: 203514

I think this should work to combine both queries and solve the opr issue:

var update = {};
if (likeAction === 'like'){
  update.$addToSet = { userIDs: userID };
  update.$inc      = { likeCount : 1 };
} else if (likeAction === 'unlike'){
  update.$pull  = { userIDs: userID };
  update.$inc   = { likeCount : -1 };
}

Like.update({ imageID: imageID }, update, ...);

Upvotes: 1

Related Questions