0

I have an update statement using Mongoose, something like this:

Model.update(condition, {
   foo: '1',
   bar: '2',
   baz: '3'
}, 
{

 new: true,
 upsert: true

}, function(err, result){

});

here is my conundrum - I only want to set the bar field if no document already exists. But always want to set the foo and baz fields, regardless.

Is there a way to do that with one query, or must I use more than one query to do this?

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • I think this question is the same question - https://stackoverflow.com/questions/24824657/how-do-i-update-mongodb-document-fields-only-if-they-dont-exist – Alexander Mills Aug 23 '17 at 19:35

1 Answers1

0

should work perfectly

condition = {}
// want to include bar with $and condition 
condition.bar = '2'
Model.findOneAndUpdate(condition, 
{
  $set:{
    foo: '1',
    baz: '3'
  }
},
{

 new: true,
 upsert: true

}, function(err, result){

});
shivshankar
  • 2,067
  • 1
  • 18
  • 28