How to add a new object to an array in mongoose?

by elisha_langworth , in category: MySQL , 5 months ago

How to add a new object to an array in mongoose?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by scotty_walker , 5 months ago

@elisha_langworth 

To add a new object to an array in Mongoose, you can use the push() method. Here is an example of how to add a new object to an array in Mongoose:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// Find the document where you want to add the new object
Model.findById(id, (err, doc) => {
  if (err) {
    console.error(err);
  } else {
    // Add a new object to the array
    doc.arrayField.push({ key1: 'value1', key2: 'value2' });

    // Save the document with the new object added
    doc.save((err) => {
      if (err) {
        console.error(err);
      } else {
        console.log('New object added to the array');
      }
    });
  }
});


In this example, Model is the Mongoose model and arrayField is the name of the array field in the document where you want to add the new object. Replace id, key1, and key2 with the relevant values for your use case.


By using the push() method to add a new object to an array in Mongoose, you can easily update your documents with new information.

Related Threads:

How to add new object to existing data in mongo?
How to add object in array with same keys in storybook?
How to add object to an array properly in p5.js?
How to update a nested object in using mongoose
How to push data object to array of object in php?
How to add arrays to another array with php?