更新另一个子文档中的子文档
Updating a subdocument within another subdocument
我的应用是 API 使用 Expressjs / Mongoose 构建的...
我有以下架构,我正在尝试更新子文档的子文档。本质上是 "phones" 数组,它是 "contacts" 数组的一部分,它是 "profile" 对象的子文档。
我正在尝试了解如何遍历对象树并进行更新。
这是我正在使用的示例模式:
{
"_id": "588b5a7d6d76c815ff6b9e7a",
"name": "Joe Smith",
"owner_id": "588b5a5d6d76c815ff6b9e79",
"__v": 1,
"contacts": [
{
"contact_name": "Jim Parks",
"_id": "588b5abd6d76c815ff6b9e7c",
"phones": []
},
{
"contact_name": "Perry Mips",
"_id": "588b5abd6d76c815ff6b31de",
"phones": []
}
]
}
我试图通过执行 findOn() 并传递记录的 ownerId 来缩小搜索范围。然后按以下方式更新 "contacts" 数组:
router.route('/:ownerId/addphone/:contactId')
.put(function(req, res) {
console.log('Req Body: ', req.body);
console.log('Req: ', req.params);
Profile.findOne({owner_id:req.params.ownerId}, function(err, profile) {
var contacts = req.body.contacts;
console.log('contacts', contacts);
profile.contacts.id(req.body._id) = contacts;
profile.save();
});
});
但这似乎不起作用。
任何帮助都会很棒!
你可以试试这个:
router.route('/:ownerId/addphone/:contactId')
.put(function(req, res) {
console.log('Req Body: ', req.body);
console.log('Req: ', req.params);
Profile.update({owner_id:req.params.ownerId,"contacts._id":req.body._id},{phones:req.body.contacts}).exec(function(err, profile) {
console.log(err)
console.log(profile)
});
});
希望对你有所帮助!!
我的应用是 API 使用 Expressjs / Mongoose 构建的...
我有以下架构,我正在尝试更新子文档的子文档。本质上是 "phones" 数组,它是 "contacts" 数组的一部分,它是 "profile" 对象的子文档。
我正在尝试了解如何遍历对象树并进行更新。
这是我正在使用的示例模式:
{
"_id": "588b5a7d6d76c815ff6b9e7a",
"name": "Joe Smith",
"owner_id": "588b5a5d6d76c815ff6b9e79",
"__v": 1,
"contacts": [
{
"contact_name": "Jim Parks",
"_id": "588b5abd6d76c815ff6b9e7c",
"phones": []
},
{
"contact_name": "Perry Mips",
"_id": "588b5abd6d76c815ff6b31de",
"phones": []
}
]
}
我试图通过执行 findOn() 并传递记录的 ownerId 来缩小搜索范围。然后按以下方式更新 "contacts" 数组:
router.route('/:ownerId/addphone/:contactId')
.put(function(req, res) {
console.log('Req Body: ', req.body);
console.log('Req: ', req.params);
Profile.findOne({owner_id:req.params.ownerId}, function(err, profile) {
var contacts = req.body.contacts;
console.log('contacts', contacts);
profile.contacts.id(req.body._id) = contacts;
profile.save();
});
});
但这似乎不起作用。
任何帮助都会很棒!
你可以试试这个:
router.route('/:ownerId/addphone/:contactId')
.put(function(req, res) {
console.log('Req Body: ', req.body);
console.log('Req: ', req.params);
Profile.update({owner_id:req.params.ownerId,"contacts._id":req.body._id},{phones:req.body.contacts}).exec(function(err, profile) {
console.log(err)
console.log(profile)
});
});
希望对你有所帮助!!