1

In mongoose, is there one line code that can save the document if it does not exist otherwise DON'T update the existing one.

I have searched online but most of the answers are about updating on the existing one document.

syl
  • 81
  • 1
  • 4

2 Answers2

7

After some lucky search, I found the following links which are really helpful:

The key is to set $setOnInsert in update params, and upsert:true in options params.

Here is a code example:

let query = {id: searchId};
let update = { 
  $setOnInsert: {
    id: searchId,
    foo: foo,
    bar: bar,
  }
};
  
let options = { upsert: true };
SampleModel.findOneAndUpdate(query, update, options)
  .catch(error => console.error(error));

Any thoughts or answers or improvements are definitely welcome!

syl
  • 81
  • 1
  • 4
1

Edit: Note that this only works for an array!

Even though this is an old post, I found something that could help people coming across this.

Instead of using the $setOnInsert, you can use $addToSet. This will add whatever data you are inserting but if the data exists, then nothing will happen.

let query = {id: searchId};
let update = { 
  $addtoSet: {
    [id: searchId]
  }
};
  
SampleModel.findOneAndUpdate(query, update)
  .catch(error => console.error(error));
Andreas C
  • 163
  • 1
  • 12