我需要使用Mongoose更新mongoDB中的子文档。这是我的架构:
{
"_id" : ObjectId("5bf66d78de019add1b8f96fe"),
"duration" : {
"start" : ISODate("2018-09-20T07:48:56.874Z"),
"end" : ISODate("2018-11-20T08:48:56.874Z")
},
"status" : "inreview",
"title" : "Good title",
"webData" : [
{
"_id" : ObjectId("5bf67288449273df45629b07"),
"webCode" : "be_mx",
"title" : "Title test MX",
"subtitle" : "Subtitle test MX",
"spins" : [],
"categories" : [],
"comments" : [],
"publishDate" : ISODate("2018-11-21T08:49:01.047Z")
},
{
"_id" : ObjectId("5bf66d7dde019add1b8f970c"),
"webCode" : "be_ar",
"title" : "Title test AR",
"subtitle" : "Subtitle test AR",
"spins" : [],
"categories" : [],
"comments" : [],
"publishDate" : ISODate("2018-11-21T08:49:01.047Z")
}
],
}
在我的更新函数中,我收到奖学金的ID,要编辑的字段的名称和新值,以及表示我需要编辑的子文档的过滤器webCode。
我正在尝试通过以下查询进行操作:
Scholarship.update({
'_id': id,
}, {
$set: {
'webData.$[i]': {
[fieldName]: newValue
}
}
}, {
multi: true,
arrayFilters: [{ "i.webCode": webCode }]
});
但是,当我执行该奖学金的子文档时,该子文档消失了,并且它用新字段创建了另一个子文档。例如,如果我将 id , fieldName “ title”, newValue 传递给“ New title”,而“ webCode”为“ be_mx”,这是我查询的结果:
{
"_id" : ObjectId("5bf66d78de019add1b8f96fe"),
"duration" : {
"start" : ISODate("2018-09-20T07:48:56.874Z"),
"end" : ISODate("2018-11-20T08:48:56.874Z")
},
"status" : "inreview",
"title" : "Good title",
"webData" : [
{
"_id" : ObjectId("5bf672884492dfsdfe4353"),
"title" : "New title",
"spins" : [],
"categories" : [],
"comments" : [],
},
{
"_id" : ObjectId("5bf66d7dde019add1b8f970c"),
"webCode" : "be_ar",
"title" : "Title test AR",
"subtitle" : "Subtitle test AR",
"spins" : [],
"categories" : [],
"comments" : [],
"publishDate" : ISODate("2018-11-21T08:49:01.047Z")
}
],
}
如果我激活猫鼬调试,我将得到以下查询:
scholarships.update({ _id: ObjectId("5bf66d78de019add1b8f96fe") }, { '$set': { 'webData.$[i]': { _id: ObjectId("5bf67288449273df45629b07"), title: 'New', spins: [], categories: [], comments: [] } } }, { multi: true, arrayFilters: [ { 'i.webCode': 'be_mx' } ] })
为什么会这样?为什么当我只想编辑标题时,为什么我的猫鼬调试显示它正在发送自旋,类别和注释数组?
已更新:
我的代码中有一些错误,这是正确的语法:
Scholarship.update({
'_id': id,
}, {
$set: {
[`webData.$[i].${fieldName}`]: newValue
}
}, {
multi: true,
arrayFilters: [{ "i.webCode": webCode }]
});