Arthur Le Calvez
Arthur Le Calvez

Reputation: 433

$push value to array with mongoose only if key is present

I would like to push a subdocument but only if a certain key is present in the update request. At the moment if the status_value key is not present in req, an empty subdocument is added with just an _id field.

My update function is as follows

Audit.findByIdAndUpdate(id, 
                       {$set:req, $push: { status: {status_value: req.status_value }} },  
                       { new: true, runValidators: true })
                       .lean().exec( function (err, audit) {
    if (err) {
      console.log(err)
      callback(err, null)
    }
    else if (!audit) {
      console.log("update_fucntion user not found")
      callback(null, null)
    }
    else {
      console.log('finished update\n\n')
      console.log(audit)
      callback(null, audit)

    }
  });

The obvious option is to put an if clause but this would therefore mean putting two Audit.findByIdAndUpdate functions. Is there a cleaner/ alternative way of accomplishing this

Upvotes: 1

Views: 154

Answers (1)

Sachin Shah
Sachin Shah

Reputation: 4533

You can check by undefine

var where = '...query'
if (req.key != undefined) {          //Key is exist in request
    where['$push'] = 'Do your stuff'
}

Upvotes: 1

Related Questions