mongoose update method code example

Example 1: mongoose save or update

// This will create another document if it doesn't exist
findByIdAndUpdate(_id, { something: 'updated' }, { upsert: true });

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: update in mongoose node js

app.put('/student/:id', (req, res) => {
    Student.findByIdAndUpdate(req.params.id, req.body, (err, user) => {
        if (err) {
            return res
                .status(500)
                .send({error: "unsuccessful"})
        };
        res.send({success: "success"});
    });

});

Example 4: mongoose updatemany example

User.update({"created": false}, {"$set":{"created": true}}, {"multi": true}, (err, writeResult) => {});

Example 5: update query in mongoose

var conditions = { name: 'bourne' } 
  , update = { $inc: { visits: 1 }}

Model.update(conditions, update, { multi: true }).then(updatedRows=>{
  
}).catch(err=>{
  console.log(err)
  
})