find one and update code example
Example 1: 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 2: findone and update mongoose
// Using queries with promise chaining
Model.findOne({ name: 'Mr. Anderson' }).
then(doc => Model.updateOne({ _id: doc._id }, { name: 'Neo' })).
then(() => Model.findOne({ name: 'Neo' })).
then(doc => console.log(doc.name)); // 'Neo'
// Using queries with async/await
const doc = await Model.findOne({ name: 'Neo' });
console.log(doc.name); // 'Neo'