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

by elisha_langworth , in category: MySQL , 10 days ago

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

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by scotty_walker , 9 days 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.