mongoose find many and update code example

Example 1: mongoose find multiple and update

Model.updateMany({}, {})

Example 2: mongoose find and update prop

var query = {'username': req.user.username};
req.newData.username = req.user.username;

MyModel.findOneAndUpdate(query, req.newData, {upsert: true}, function(err, doc) {
    if (err) return res.send(500, {error: err});
    return res.send('Succesfully saved.');
});

Example 3: mongoose response to object

MyModel.findOne().lean().exec(function(err, doc) {
    doc.addedProperty = 'foobar';
    res.json(doc);
});

Example 4: 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'