Express JS Mongo DB Mongoose ODM Node JS

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

mongoDB Monoogse Schema
Written by VithalReddy.M.B

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
        }
    }
);

 

READ  Get User's IP address in Node.js (Express.js)

and you’re successfully pulled 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.

About the author

VithalReddy.M.B

Vithalreddy.M.B is the Editor of VMRworld.com & stackFame.com with a focus on startups, Startup News, Business, and Technology.He is also an Electrical & Electronics Engineer, Technology Lover, and Entrepreneur by choice.Started His first startup at 21.