pulankit
pulankit

Reputation: 565

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!")
    }
}) 

Upvotes: 4

Views: 68

Answers (2)

jerry
jerry

Reputation: 745

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

Upvotes: 1

Shaishab Roy
Shaishab Roy

Reputation: 16805

you can try this one

user.findOneAndUpdate({fbPsid:sender, $where:'this.referal.length < 5'}, 
    {$set:{status: {state: -11}},$push:{"referal":{name:'',phonenumber:'',email:''}}}, 
    {new:true},
    function(error, updateDoc) {
      if(error) {
        // handle error
      } else {
        // success action
      }
});

Upvotes: 0

Related Questions