mongoose update a document 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: save or update mongoose

// SAVE NEW OR UPDATE EXISTING COLLECTION
AnnoucementTagsModel.findOneAndUpdate({_id: announcementId}, newAnnoucementTags, {upsert: true}, function (err, doc) {
	if (error) throw new Error(error);
	console.log("succesfully saved");
});

Example 4: 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)
  
})

Example 5: update in mongoose node js

router.patch('/:id', (req, res, next) => {
    const id = req.params.id;
    Product.findByIdAndUpdate(id, req.body, {
            new: true
        },
        function(err, model) {
            if (!err) {
                res.status(201).json({
                    data: model
                });
            } else {
                res.status(500).json({
                    message: "not found any relative data"
                })
            }
        });
});