[英]How to remove the specific element in an array of objects in mongoose using nodejs?
[英]How can I push a value to a specific array index using mongoose in nodejs?
我正在嘗試使用以下代碼在數組的特定索引處將值推入數組:
Freezer.update(conditions, {$push: {shelves[shelfindex] : {"rackname": rackname, "columns": columns, "rows": rows, "spaces" : []}}}, function (err, doc){
console.log(doc);
})
這里的架子索引是當前架子的索引,我在前面有一個for循環(代碼未顯示)找到。
它不起作用(該程序甚至無法啟動)。 我收到以下錯誤:
SyntaxError: Unexpected token [
我的書架陣列設置如下:
[{"racks":[],"shelfname":"Shelf 1"},{"racks":[],"shelfname":"Shelf 2"},{"racks":[],"shelfname":"Shelf 3"}]
因此,例如,如果我嘗試將機架數據推送到“架子1”,則嘗試將其推送到:
shelves[0].racks
有解決方案的想法嗎?
如果您展示了Freezer模型架構,將會有所幫助。 但是,以下示例基於示例數據(示例):
{
"_id" : ObjectId("565236570f7f257d5feffa10"),
"shelves" : [
{
"racks" : [],
"shelfname" : "Shelf 1"
},
{
"racks" : [],
"shelfname" : "Shelf 2"
},
{
"racks" : [],
"shelfname" : "Shelf 3"
}
]
}
因此,將機架數據推入mongo shell的"Shelf 1"
機架將使用positional $
運算符,該運算符僅支持一個級別的深度,並且僅支持其更新中的第一個匹配元素。 注意, shelves
陣列字段必須出現在查詢文檔的一部分,因此, { "shelves.shelfname": "Shelf 1" }
db.freezer.update(
{ "shelves.shelfname": "Shelf 1" },
{
"$push": {
"shelves.$.racks": {
"rackname": 1,
"columns": 3,
"rows": 2,
"spaces" : []
}
}
}
);
現在,如果您知道特定的數組索引,則使用括號表示法創建更新文檔:
var update = { "$push": {} },
condition = { };
condition["shelves.shelfname"] = "Shelf "+ shelfindex + 1;
update["$push"]["shelves."+ shelfindex +".racks" ] = {
"rackname": rackname,
"columns": columns,
"rows": rows,
"spaces" : []
};
db.freezer.update(condition, update);
在您的node.js中,這將類似於但具有回調:
Freezer.update(conditions, update, function (err, doc){
console.log(doc);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.