mongoose update push to array code example
Example 1: mongodb push to arry in update
db.collection.update({_id:xx}, {$push:{letters : {$each:['first one'], $position:0}}})
Example 2: 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 3: 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 4: how to append data to a field in mongoose model
//mongoose appending data
var objFriends = { fname:"fname",lname:"lname",surname:"surname" };
Friend.findOneAndUpdate(
{ _id: req.body.id },
{ $push: { friends: objFriends } },
function (error, success) {
if (error) {
console.log(error);
} else {
console.log(success);
}
});
)
Example 5: mongodb push to arry in update
db.collection.update({_id:xx}, {$pop:{letters : -1}})
Example 6: add in to array mongoose
// With { $push: { field: element } }
// Example:
const elementToPush = { a: 1, b: 2 };
const body = { $push: { arrayField: elementToPush } };
model.patch(id, body);