Push and Pop Items Into MongoDB Array Via Mongoose in Node.js

How To Push or Pop Items Into MongoDB Document Array Via Mongoose in Node.js (Express.js)

If you’re Developing your Rest API’s using Node.js or Express.js, Then You’re probably using MongoDB as Database for Storing Data and Probably with mongoose ODM for working with MongoDB Database.Now as you’re DB starts to grow and you have multiple collections and they are related to each other and soon, you need to work with array’s inside in MongoDB document and now you want to push and pop from that array, In this MongoDB How-To Tutorial, we are going to learn How to Push items into mongo Array with an example.


How To Push and Pop Items Into MongoDB Document Array

Consider the following document, which is USER document, which has an array of Friends:

USER doc

Now, You want edit friends array, when you want to add or remove friend to friends array.First, we will push a friend into an array with the mongoose in nodejs app.

// find by document id and update and push item in array
users.findByIdAndUpdate(userID,
    {$push: {friends: friend}},
    {safe: true, upsert: true},
    function(err, doc) {
        if(err){
        console.log(err);
        }else{
        //do stuff
        }
    }
);

and you’ve successfully pushed item in a MongoDB document.Now we will learn how to pop or remove an item from MongoDB document array.

// find by document id and update and pop or remove item in array
users.findByIdAndUpdate(userID,
    {$pull: {friends: friend}},
    {safe: true, upsert: true},
    function(err, doc) {
        if(err){
        console.log(err);
        }else{
        //do stuff
        }
    }
);

and you’re successfully poped or removed an item in a MongoDB document.

Conclusion:

It’s very easy to handle data with mongoose and MongoDB.So that you’ve to spend less time with data handling in MongoDB, Focus on your business logic of Rest API’s.

This article first appeared on: stackFAME.com

Push and Pop Items Into MongoDB Array Via Mongoose in Node.js

AUTHOR

over 1 year ago

You shoud use $addToSet instead of $push. With $addToSet if the thing you want to push in the array is already present, it won't push it again.

thanks for the quick suggestion, i will update.

READ NEXT

Boostlog is an online community for developers
who want to share ideas and grow each other.

Delete an article

Deleted articles are gone forever. Are you sure?