mongoose document updateOne push code example

Example 1: add items to a list in a document monoose

const {name , id} = req.body
    Category.update(
        {_id: id}, 
        {$push: {items: {"name": name}}},{new: true, upsert: true }).exec();
        res.sendStatus(200)

Example 2: how to append data to a field in mongoose model

exports.addFriend = function (req, res, next)
{
var friend = {"firstName": req.body.fName, "lastName": req.body.lName};
Users.findOneAndUpdate({name: req.user.name}, {$push: {friends: friend}});
};

Example 3: mongoose updatemany example

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

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

Tags:

Misc Example