mongodb findoneandupdate code example

Example 1: mongoose findoneandupdate

// note: this uses async/await so it assumes the whole thing 
// is in an async function 

const doc = await CharacterModel.findOneAndUpdate(
  { name: 'Jon Snow' },
  { title: 'King in the North' },
  // If `new` isn't true, `findOneAndUpdate()` will return the
  // document as it was _before_ it was updated.
  { new: true }
);

doc.title; // "King in the North"

Example 2: mongofindoneandupate

try {
db.grades.findOneAndUpdate(
   { "name" : "A.B. Abracus" },
   { $set: { "name" : "A.B. Abracus", "assignment" : 5}, $inc : { "points" : 5 } },
   { sort: { "points" : 1 }, upsert:true, returnNewDocument : true }
);
}
catch (e){
   print(e);
}

Example 3: returned value by findOneAndUpdate

const filter = { age: 17 };
const doc = { $set: { name: "Naomi" } };
const options = { new: true };

Cat.findOneAndUpdate(filter, doc, options, (err, doc) => {
    if (err) console.log("Something wrong when updating data!");
    console.log(doc);
});

Example 4: mongodb findoneandupdate return updated

//pass the {new: true} as the third option, if using mongodb driver use {returnOriginal: true}                                                      V--- THIS WAS ADDED
Cat.findOneAndUpdate({age: 17}, {$set:{name:"Naomi"}}, {new: true}, (err, doc) => {
    if (err) {
        console.log("Something wrong when updating data!");
    }

    console.log(doc);
});