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

Article Contents

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 schema mongodb

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 pulled or removed an item in a MongoDB document.

See also  Google Recaptcha Node.JS (Express.js) Tutorial

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.

1 thought on “Push and Pop Items Into MongoDB Array Via Mongoose in Node.js”

  1. What does the friend variable look like? Is it just a string? I’m trying to implement your example with my own project but I’m trying to push a new object into an array. I have been struggling with this problem and I’ve found similar examples like yours in the mongoose documentation and a couple other places but they are all with very simple schemas.

    Reply

Leave a Comment