Using nodejs and mongoose to update array

Have a Database Problem? Speak with an Expert for Free
Get Started >>

Introduction

Working with arrays can be complicated. Updating can be more complicated. One should work carefully while performing update operations on arrays. Mongoose provides a few operators to update arrays such as $addToSet, $push, $pop, etc. In this article, we will discuss how to use such operators to perform update operations on arrays in nodejs.

First we want to use a set of data to demo with. We will use the details collection shown here:

1
2
3
{ "_id" : ObjectId("5e158429a7b6505cd15e8097"), "name" : "John", "age" : 21, "locations" : [ "New York", "Chicago" ] }
{ "_id" : ObjectId("5e158439a7b6505cd15e8098"), "name" : "Sam", "age" : 24, "locations" : [ "New York" ] }
{ "_id" : ObjectId("5e158453a7b6505cd15e8099"), "name" : "Lisa", "age" : 27, "locations" : [ "Washington DC", "Texas" ] }

We will use the postman tool to perform endpoint testing. You can download the postman tool from www.getpostman.com.

As we will perform an update operation, we have to make a PUT request. The following route handler will be invoked when the endpoint ‘/update’ is executed.

NOTE We created our routes using a great package for NodeJS called express.

1
router.route("/update").put(function(req, res) {});

Let’s discuss how to update the array using mongoose operators in nodejs.

$addToSet

The $addToSet operator adds values in an array if they are not already present in it. We specify an array of values and it inserts only those values that are not present in it. Let’s add a few values to the locations array where the name is “John”.

1
2
3
4
5
6
7
8
9
10
11
12
13
router.route("/update").put(function(req, res) {
  details.updateOne(
    { name: "John" },
    { $addToSet: { locations: ["New York", "Texas", "Detroit"] } },
    function(err, result) {
      if (err) {
        res.send(err);
      } else {
        res.send(result);
      }
    }
  );
});

As of now, the document where the value of the name field is “John” has two values in the locations array – New York and Chicago. In the update operation, we will add three new values to it using the $addToSet operator – New York, Texas, and Detroit. One of these three is already present in the locations array. Let’s execute it and see what happens.

Image from Gyazo

It returns an object. Here, the value of nModified is 1. This means, one document was updated. Let’s check through the mongo shell.

Image from Gyazo

Two values were added – Texas and Detroit. It did not add New York because it was already present. This is how $addToSet works.

$push

The $push operator is somewhat similar to $addToSet operator. The difference is that it adds values to an array even if they are already present. Let’s add “New York” where the value of the name field is “John”.

1
2
3
4
5
6
7
8
9
10
11
12
13
router.route("/update").put(function(req, res) {
  details.updateOne(
    { name: "John" },
    { $push: { locations: ["New York"] } },
    function(err, result) {
      if (err) {
        res.send(err);
      } else {
        res.send(result);
      }
    }
  );
});

Let’s execute and see what happens.

Image from Gyazo

The $push operator added “New York” in the locations array even it was already present there. This is the difference between $addToSet and $push operator.

$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. “New York” from the document where the value of the name field is “John”.

1
2
3
4
5
6
7
8
9
10
11
12
router.route("/update").put(function(req, res) {
  details.updateOne({ name: "John" }, { $push: { locations: 1 } }, function(
    err,
    result
  ) {
    if (err) {
      res.send(err);
    } else {
      res.send(result);
    }
  });
});

Image from Gyazo

Yes! The last value was deleted. Now, let’s remove the very first value, also “New York”. This time, we have to give -1 as the value.

1
2
3
4
5
6
7
8
9
10
11
12
router.route("/update").put(function(req, res) {
  details.updateOne({ name: "John" }, { $push: { locations: -1 } }, function(
    err,
    result
  ) {
    if (err) {
      res.send(err);
    } else {
      res.send(result);
    }
  });
});

Image from Gyazo

Yes! The first value was also deleted.

Conclusion

Thank you for checking out our knowledge base article! We hoped you enjoyed this demonstration of some of the functionality we can use to update arrays with mongoose.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.