pulankit pulankit - 1 year ago 65
Node.js Question

Condtional Update in MongoDb

Is there a better way of doing this conditional update with only one db call i.e only using

user.update
?

user.findOne({ fbPsid: sender }, 'referal', function (err, res) {
if (res.referal.length < 5 ) {
user.update(
{ fbPsid: sender },
{
$set: { status: { state: -11 } },
$push: {
"referal": {
name: '',
phonenumber: '',
email: ''
}
}
}, function (err, res){}
);
} else {
sendTextMessage(sender, "You have already completed Your Five Referal!")
}
})

Answer Source

You can use the following query with mongodb 3.2+:(or findAndModify for older versions)

user.findOneAndUpdate({fbPsid:sender,'referal.4':{$exists:false}}, 
    {$set:{status: {state: -11}},$push:{"referal":{name:'',phonenumber:'',email:''}}}, 
    {new:true},
    function(error, result) {
      if(error) {
         console.log(error)
      } else {
        console.log(result);
      }
});

referal.4 : {$exists:false} ==> checking for index 4 in array. If found any record, means array length less than 5.

Note when using $where: $where evaluates JavaScript and cannot take advantage of indexes. Refer $where operator

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download