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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-06-18 14:38:57 +0000
Seen: 10 times
Last updated: Jun 18 '23
What is the process of integrating API data into MongoDB using Spark/Python?
How can additional fields that have been transformed be queried in MongoDB?
What is the difference between indexing in Elasticsearch and MongoDB?
When data is updated in MongoDB, why does Logstash not reflect the changes?
How can the Mongo Operator be used to deploy MongoDB in EKS/EFS?
How can data be extracted from Azure DocumentDB for exporting purposes?
How can I link or integrate mongodb with Google Data Studio?