1// note: this uses async/await so it assumes the whole thing
2// is in an async function
3
4const doc = await CharacterModel.findOneAndUpdate(
5 { name: 'Jon Snow' },
6 { title: 'King in the North' },
7 // If `new` isn't true, `findOneAndUpdate()` will return the
8 // document as it was _before_ it was updated.
9 { new: true }
10);
11
12doc.title; // "King in the North"
1// Update the document using `updateOne()`
2await CharacterModel.updateOne({ name: 'Jon Snow' }, {
3 title: 'King in the North'
4});
5
6// Load the document to see the updated value
7const doc = await CharacterModel.findOne();
8doc.title; // "King in the North"
1const userObjectId = mongoose.Types.ObjectId(userIdString);
2
3await UserModel.updateOne({ _id: userObjectId }, { $set: { isVerifiedEmail: true } }).catch(
4 error => {
5 console.log(error);
6 }
7);
8console.log('user updated');
1// Using queries with promise chaining
2Model.findOne({ name: 'Mr. Anderson' }).
3 then(doc => Model.updateOne({ _id: doc._id }, { name: 'Neo' })).
4 then(() => Model.findOne({ name: 'Neo' })).
5 then(doc => console.log(doc.name)); // 'Neo'
6
7// Using queries with async/await
8const doc = await Model.findOne({ name: 'Neo' });
9console.log(doc.name); // 'Neo'