4

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!")
    }
}) 
Community
  • 1
  • 1
pulankit
  • 555
  • 4
  • 9
  • 1
    Check `findAndModify` https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/ – michelem Jul 13 '16 at 08:36

2 Answers2

1

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

jerry
  • 745
  • 6
  • 20
0

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
      }
});
Shaishab Roy
  • 16,335
  • 7
  • 50
  • 68
  • looks like a good approach but could u tell me what would it return if this.referal.length becomes equal to 5.Can i write a handle case for that?I am new to Mongo Db – pulankit Jul 15 '16 at 14:53