mongodb - 使用 Mongoose 将嵌套对象添加到对象
问题描述
我正在尝试在 Mongoose 中添加一个嵌套项目,但我似乎无法让它工作。我正在尝试将“消息”对象添加到现有的“子项”对象
我在 MongoDB 中的 JSON
{
"_id" : ObjectId("5c33438d3d1e1323111fce6e"),
"title" : "Nieuws",
"__v" : 0,
"subitem" : [
{
"title" : "Nieuwsberichten",
"messages" : [
{
"title" : "bericht1"
},
{
"title" : "bericht2"
}
]
},
{
"title" : "Nieuwsarchief"
},
{
"title" : "Nieuwsbrief"
}
]
}
在快递:
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'});
解决方案
您的架构与您的 JSON 对象不匹配。在您的 Schema 消息中是一个对象,而在 JSON 中它是一个对象数组。
尝试以下架构:
var menuItems = new mongoose.Schema({
title : String,
subitem : {
title: String,
messages : [{
title: String,
text: String
}]
}
}, {collection: 'menu_items'});
推荐阅读
- sql - 在同一个 SQL 查询中使用 rank() 和 count()
- python - 如何有效地获取 Dataframes 中每个行值的平均值
- mysql - MySQL - 无法删除或更新父行
- swift - Xcode 测试目标在主目标中找不到类
- ios - Swift/Realm 所需的 init() 在调用中有额外的参数
- c# - Unity如何在场景更改后重置分数?
- python - 如何在自定义 Tensorflow 层中支持混合精度?
- html - Css动画过渡变换不起作用
- java - 如何在最短的执行时间内解决以下问题(Java)
- google-apps-script - 如何从另一个 GAS 项目访问脚本属性