Push and pop in mongoose
Introduction
Arrays are one of the most commonly used data structures in the programming world. They are perfect to store elements of the same data types. We can store any type of data in arrays. While working with databases, we may need to store data in an array. For example, the following MongoDB documents contain a field that stores an array of Strings.
1 2 3 | { "locations" : ["New York" , "Texas", "Chicaggo"] } |
Mongoose provides quite a few methods and operators that can be used on arrays to modify them. Two of these operators are $push and $pop. In this article, we will discuss how to use $push and $pop in mongoose.
We will use the details collection.
1 2 3 | { "_id" : ObjectId("5dfc768cb7ddf9e294ba5d16"), "name" : "John", "age" : 21, "locations" : [ "New York", "Texas", "Chicago" ] } { "_id" : ObjectId("5dfc769bb7ddf9e294ba5d17"), "name" : "Sam", "age" : 25, "locations" : [ "Texas" ] } { "_id" : ObjectId("5dfc76cdb7ddf9e294ba5d18"), "name" : "Lisa", "age" : 29, "locations" : [ "Texas", "Chicago" ] } |
We will the postman tool for testing. You can download it from www.getpostman.com.
$push
The $push operator adds an element at the end of an array. We can add as much as elements we want. Let’s add two more elements in the “locations” where the value of the name field is “Sam”.
The following route handler will be invoked when the endpoint ‘/updateLocations’ will be executed.
NOTE We are using the express framework in NodeJS to define our routes.
1 | router.route("/updateLocations").put(function(req, res) {}); |
As we are performing an Update operation, we will make a PUT request. There are a few methods mongoose provides for updating documents. We will use the updateOne() method. This method updates a single document. So let’s add the updateOne() method into the route handler.
1 2 3 4 5 6 7 | details.updateOne({ name: "Sam" }, {}, function(err, result) { if (err) { res.send(err); } else { res.send(result); } }); |
The first parameter of the updateOne() method is the query.
1 | {"name" : "Sam"} |
The second parameter is the update. Here, we will define the $push operator. Currently, it is empty. So let’s try to understand how to use the $push operator.
1 | { $push : {"locations" : ["Washington DC", "California"]}} |
The value of the $push operator is an object. That object should contain a key-value pair. The key should be the field in which the values are to be added. The value should be an array of elements. Let’s add it to the updateOne() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 | router.route("/updateLocations").put(function(req, res) { details.updateOne( { name: "Sam" }, { $push: { locations: ["Washington DC", "California"] } }, function(err, result) { if (err) { res.send(err); } else { res.send(result); } } ); }); |
Let’s execute it using the postman tool.
The updateOne() method returns an object. The value of the nModified field is 1, this means, one document was updated. We can use the mongo shell to verify it.
Yes! Two elements were added at the end.
$pop
The $pop operator removes an element from an array, either from starting or the end. We will remove one element from both sides. The syntax of $pop is quite similar to the $push operator. The only difference is, instead of an array as the value, we either use 1 or -1. If the value specified is 1, the last element will be removed, and if the value is -1, the first element will be removed. Let’s start by removing the last element, i.e. “California”.
1 | { $pop : {"locations" : 1}} |
Let’s add it to the updateOne() method and then execute the route using the postman tool.
1 2 3 4 5 6 7 8 9 10 11 12 | router.route("/updateLocations").put(function(req, res) { details.updateOne({ name: "Sam" }, { $pop: { locations: 1 } }, function( err, result ) { if (err) { res.send(err); } else { res.send(result); } }); }); |
One document was updated. Let’s check through the mongo shell.
Yes, the last element was deleted. Let’s delete the first element too, i.e. “Texas”.
1 | { $pop : {"locations" : -1}} |
Let’s add it to the updateOne() method.
1 2 3 4 5 6 7 8 9 10 11 12 | router.route("/updateLocations").put(function(req, res) { details.updateOne({ name: "Sam" }, { $pop: { locations: 1 } }, function( err, result ) { if (err) { res.send(err); } else { res.send(result); } }); }); |
After executing the first element should be deleted because the value we provided is -1. Let’s check through the mongo shell.
Yes! The first element was deleted.
Conclusion
This is was a simple demo of how we can use the $push and $pop functionality within mongoose. Thank you for joining us for another ObjectRocket knowledge base tutorial.
Pilot the ObjectRocket Platform Free!
Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.
Get Started