我正在尝试在Mongoose中添加一个嵌套项目,但是我似乎无法使其正常工作。我正在尝试将“消息”对象添加到现有的“子项”对象
我在MongoDB中的JSON
{
"_id" : ObjectId("5c33438d3d1e1323111fce6e"),
"title" : "Nieuws",
"__v" : 0,
"subitem" : [
{
"title" : "Nieuwsberichten",
"messages" : [
{
"title" : "bericht1"
},
{
"title" : "bericht2"
}
]
},
{
"title" : "Nieuwsarchief"
},
{
"title" : "Nieuwsbrief"
}
]
}
在Express中:
postController.postArticles = function(req, res,item) {
var id = req.body.id;
var saveData = {
title: req.body.title,
text: req.body.text
};
item.update({_id: id}, {$push:{'subitem.messages': saveData}},(err, result) => {
});
};
猫鼬模型:
var menuItems = new mongoose.Schema({
title : String,
subitem : {
title: String,
messages : {
title: String,
text: String
}
}
}, {collection: 'menu_items'});
答案 0 :(得分:0)
您的架构与您的JSON对象不匹配。 在您的Schema消息中是一个对象,而在JSON中则是一个对象数组。
尝试以下架构:
var menuItems = new mongoose.Schema({
title : String,
subitem : {
title: String,
messages : [{
title: String,
text: String
}]
}
}, {collection: 'menu_items'});