Answers for "add additional field in mongodb document if it is not exist while find one and update"

0

add additional field in mongodb document if it is not exist while find one and update

const filter = { name: 'Will Riker' };
const update = { age: 29 };

await Character.countDocuments(filter); // 0

let doc = await Character.findOneAndUpdate(filter, update, {
  new: true,
  upsert: true // Make this update into an upsert
});
doc.name; // Will Riker
doc.age; // 29
Posted by: Guest on March-15-2022
0

add additional field in mongodb document if it is not exist while find one and update

Using the upsert option, you can use findOneAndUpdate() as a 
find-and-upsert operation. An upsert behaves like a normal findOneAndUpdate() 
if it finds a document that matches filter. But, if no document matches filter, 
MongoDB will insert one by combining filter and update as shown below.


const filter = { name: 'Will Riker' };
const update = { age: 29 };

await Character.countDocuments(filter); // 0

let doc = await Character.findOneAndUpdate(filter, update, {
  new: true,
  upsert: true // Make this update into an upsert
});
doc.name; // Will Riker
doc.age; // 29
Posted by: Guest on March-15-2022

Code answers related to "add additional field in mongodb document if it is not exist while find one and update"

Code answers related to "Javascript"

Browse Popular Code Answers by Language