1var query = {'username': req.user.username};
2req.newData.username = req.user.username;
3
4MyModel.findOneAndUpdate(query, req.newData, {upsert: true}, function(err, doc) {
5 if (err) return res.send(500, {error: err});
6 return res.send('Succesfully saved.');
7});
8
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"
1User.update({"created": false}, {"$set":{"created": true}}, {"multi": true}, (err, writeResult) => {});
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'
1var conditions = { name: 'bourne' }
2 , update = { $inc: { visits: 1 }}
3
4Model.update(conditions, update, { multi: true }).then(updatedRows=>{
5
6}).catch(err=>{
7 console.log(err)
8
9})