Arrays 如何更新特定数组';mongoose中另一个数组中的对象?
我有这样一个模式:Arrays 如何更新特定数组';mongoose中另一个数组中的对象?,arrays,mongodb,mongoose,mern,Arrays,Mongodb,Mongoose,Mern,我有这样一个模式: 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
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});
await NoteClusterSchema.updateMany({idGroup: req.body.idGroup},
{
noteInfo: {$push: {authors: {name:
req.body.name}}}
})
noteInfo
的一个例子是
noteInfo: [{
title: "Hello",
Description: "Hello World",
authors:[
{name: "Marcelo", id: "1234123123"},
{name: "Pancho", id: "12341345344"}
]
}]
例如,如何在authors数组中更新“Marcelo”的名称?(假设是,如果用户更改了它的名称。我知道在这种特定情况下,我可以只输入_id,但在我的真实模式中,我要更新的不是用户)
我想到了这样的事情:
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});
await NoteClusterSchema.updateMany({idGroup: req.body.idGroup},
{
noteInfo: {$push: {authors: {name:
req.body.name}}}
})
但是通过这种方式,它不知道所有noteInfo数组中的哪个会更新,或者它会创建一个新的authors
数组,而更改noteInfo:{$push:{code>$push:{noteInfo:
只会创建一个新的noteInfo
数组
那么,如何使用UpdateMany方法在另一个数组中的数组中更新此特定对象呢?使用$set选项findOneAndUpdate应该可以解决您的问题:
NoteClusterSchema.findOneAndUpdate(
{idGroup: req.body.idGroup},
{$set: {"noteInfo.$[element].value": "YOUR_NEW_NAME" } },
{
arrayFilters: [{ "element.name": "Marcelo" }],
new: true
}
)
注意:您必须添加arrayFilters选项,以便以数组中的特定元素为目标
这是否回答了您的问题?