我试图更新使用ExpressJS在猫鼬嵌套子文档,但我似乎无法得到它的工作。该位置$
操作不经过超过1级,我已经使用arrayFilters
尝试,但我似乎无法得到那个工作要么。
这是该文件:
{
"_id" : ObjectId("5c52b017d9133d14876d2493"),
"title" : "main_item",
"subitem" : [
{
"_id" : ObjectId("5c52f4e74ef7482a646fc264"),
"title" : "sub_item",
"messages" : [
{
"_id" : ObjectId("5c5303fa4b20df2d33d6eb08"),
"type" : "single_article",
"date" : "Jan 31, 2019",
"title" : "item",
"text" : "<p>item text</p>"
},
{
"_id" : ObjectId("5c53040b4b20df2d33d6eb09"),
"type" : "single_article",
"date" : "Jan 31, 2019",
"title" : "item 2",
"text" : "<p>item 2 text</p>"
}
]
}
],
"__v" : 0
}
postController.updateMessage = function(req, res, item) {
var id = req.body.id;
var sub_id = req.body.sub_id;
var saveData = {
title: req.body.title,
text: req.body.text
};
item.updateOne({'subitem._id': id}, {$set: {'subitem.$[el1].messages.$[el2]': saveData}}, {arrayFilters:[{"el1._id": id},{"el2._id": sub_id}]})
};
猫鼬模型:
var submessages = mongoose.Schema({
date: String,
type: String,
title: String,
text: String
});
var subitems = new mongoose.Schema({
title: String,
messages: [submessages]
});
var menuItems = new mongoose.Schema({
title : String,
subitem: [subitems]
}, {collection: 'menu_items'});
module.exports = mongoose.model("menu_items", menuItems);
我不知道我是否有关于如何准确地解决您的问题的答案,但我要建议一个解决方案,我认为显著增加组织的在你的代码的水平...
(1)首先,每个这些架构应该被导出为独立的模型(我建议他们各自在单独的文件)
(2)其次,在你subitems
和menuItems
模式,使信息和子项的引用。如果你按照我提出的第一个建议,那么你可以让你的菜单项的模式类似如下:
menuItems.js
const menuItems = new mongoose.Schema({
title : String,
subitem: {
type: mongoose.Types.ObjectId,
ref: 'sub_items'
}
});
module.exports = mongoose.model("menu_items", menuItems);
凡sub_items
是您已导出你的子项目模型的名称。使用您的子项的模型类似的格式太多,但我会告诉你这样做,因为我不想偷所有的乐趣;)
(3)现在,这些都是引用,当你需要改变一个子项,一个菜单项的引用,你只需要更新实际的子项。你不再需要通过菜单项对象更新子项,因为参考子项永远不会改变!
我希望这有帮助。应该更加有组织你现在,应该是更易于更新您的子项和分消息