javascript

Learn How to push an element to array in Mongoose


In this article, you are going to learn about how to push an element to an array in the Mongoose.

An array is the most common data structure in all programming languages. You can store multiple data into the array. In databases like mongoose, arrays are widely used. You can store an array of strings, an array of integers, and so on. Moreover, you may also push an element in a specific array.

Mongoose lets you perform many different ways to modify an array. The $push operator is one of the popular ways to modify an array. With the help of this operator, you can add an element at the end of an array in mongoose. To do this, we will be using the following details information of students where each student has their name, age, and hobbies. See the details below:

1. { "_id" : ObjectId("615feb693e144eeb6ee3ef5e"), 
                "name" : "Alex",
                "age" : 19, 
                "hobbies" : [ "Singing", "Reading Books", "Writing" ] }
2. { "_id" : ObjectId("615976357dbb9dbc8a469b48"), 
                "name" : "Deven", 
                "age" : 22, 
                "hobbies" : [ "Programming" ] }
3. { "_id" : ObjectId("6184bb317e1287a3d11e741a"), 
                "name" : "Strac", 
                "age" : 23, 
                "hobbies" : [ "Cricket", "Writing" ] }

We know that by using $push operator we can add elements into the array in Mongoose. Now we will add another element in Deven’s hobbies array with the help of this operator. See the below code example:

router.route("/updateHobbies").put(function(req, res) {
  details.updateOne(
    { name: "Deven" },
    { $push: { hobbies : [ "Writing"] } },
    function(err, result) {
      if (err) {
        res.send(err);
      } else {
        res.send(result);
      }
    }
  );
});

Here, we define the route as updateHobbies and apply a PUT request. After that we apply Mongoose updateOne() method and use the $push operator to update it. This is empty now but the moment /updateHobbies is being hit the data will be updated and the element will be pushed into the array. The output in your database will be look like this:


/*
        {
         "_id" : ObjectId("615976357dbb9dbc8a469b48"), 
                "name" : "Deven", 
                "age" : 22, 
                "hobbies" : [ "Programming", "Writing" ] }
*/

You can see that a new element has been added in the deven’s hobbies array which is “Writing” and this is the way you can push an element to an array in Mongoose.


Share on social media

//