mongoose findone and update 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: mongoose updateone example
// Update the document using `updateOne()`
await CharacterModel.updateOne({ name: 'Jon Snow' }, {
title: 'King in the North'
});
// Load the document to see the updated value
const doc = await CharacterModel.findOne();
doc.title; // "King in the North"
Example 3: 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'