我想将项目推送到项目数组(根文档>类别>子类别>项目)
我正在使用NodeJS和MongoDB npm包
我的文档结构应如下所示
{
"_id": "572a77641b24ed3404f43690"
"categories": [
{
"id": "572bbac072d7ee3026a69467"
"Name": "Foods",
"subcategories": [
{
"id": "572a777c1b24ed3404f43691",
"Name": "Pizza"
"items": [
{
"id": "572ba1666ca263303121acd4"
"Name": "4 Seasons",
"Price": "6.0"
}
]
}
]
}
]
}
我目前的代码是
app.post("/item/:subcatid", function(req, res) {
var subId = req.params.subcatid;
var item = req.body;
item.id = new ObjectId();
items.update({ "categories.subcategories.id": ObjectId(subId) }, { $push: { "categories.0.subcategories.$.items": item } }, function(err, result) {
res.send(result);
});
});
我该怎么办?
答案 0 :(得分:0)
刚刚找到了一个解决方案,但不是干净的,但工作正常!
app.post("/item/:subcatid", function(req, res) {
var subId = req.params.subcatid;
var item = req.body;
item.id = new ObjectId();
items.findOne({ "categories.subcategories.id": ObjectId(subId) }, { "categories.subcategories.$": 1 }, function(err, doc) {
for (var i = 0; i < doc.categories[0].subcategories.length; i++) {
var elem = doc.categories[0].subcategories[i];
if (elem.id == subId) {
items.update({ "categories.subcategories.id": ObjectId(subId) }, { $push: { ["categories." + i + ".subcategories.$.items"]: item } }, function(err, result) {
res.send(result);
});
break;
}
}
});
});