I have a Schema like this:
const NoteClusterSchema = new Schema({
noteInfo: [{
title: String,
Description: String,
authors:[{
name: String, Id: String
}]
}],
idGroup: String //this is the group of the people that are working on the proyect
}, {timestamps:true});
An example of noteInfo
would be
noteInfo: [{
title: "Hello",
Description: "Hello World",
authors:[
{name: "Marcelo", id: "1234123123"},
{name: "Pancho", id: "12341345344"}
]
}]
How can I update, for example, in the authors array specifically the name of "Marcelo"? (suppose that it is if the user changes it's name. I know that in this specific case I could put just the _id, but in my real Schema it isn't a user the thing I want to update)
I thought of something like this:
await NoteClusterSchema.updateMany({idGroup: req.body.idGroup},
{
noteInfo: {$push: {authors: {name:
req.body.name}}}
})
But in this way, it won't know which of all the noteInfo arrays update or it would create a new authors
array, and changing noteInfo: {$push:
$push: {noteInfo:
will only create a new noteInfo
array.
So, how could I update this specific object in an array inside another array with the UpdateMany method?
findOneAndUpdate with the $set option should solve your problem:
NoteClusterSchema.findOneAndUpdate(
{idGroup: req.body.idGroup},
{$set: {"noteInfo.$[element].value": "YOUR_NEW_NAME" } },
{
arrayFilters: [{ "element.name": "Marcelo" }],
new: true
}
)
Note: You have to add the arrayFilters option in order to target the specific element in the array.
https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.