Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To update or overwrite elements in an array using Mongoose and Node.js, you can use the findOneAndUpdate method. Here is an example:

const MyModel = require('./myModel');

MyModel.findOneAndUpdate(
  { _id: objectId },
  { $set: { 'myArray.$[elemIndex].field': newValue } },
  { arrayFilters: [{ 'elemIndex.id': elementId }] }
)
  .then(() => console.log('Array element updated successfully'))
  .catch((err) => console.log('Error updating array element: ', err));

In this example, MyModel is the Mongoose model for the document that contains the array you want to update. objectId is the ID of the document you want to update, myArray is the name of the array field you want to update, elemIndex is the index of the element you want to update, and field is the name of the field you want to update within that element. newValue is the new value you want to set for that field.

The arrayFilters option is used to specify which element of the array you want to update. In this example, we specify the id of the element we want to update using elementId.

Note that the arrayFilters option is only available in MongoDB 3.6 or later. If you are using an older version of MongoDB, you can use the $where operator instead, but be aware that it can be less performant.