[英]How can I push a value to a specific array index using mongoose in nodejs?
I'm trying to push values to an array at a specific index of an array using the following code: 我正在尝试使用以下代码在数组的特定索引处将值推入数组:
Freezer.update(conditions, {$push: {shelves[shelfindex] : {"rackname": rackname, "columns": columns, "rows": rows, "spaces" : []}}}, function (err, doc){
console.log(doc);
})
where shelfindex is the index of the shelf at hand, that I find with a preceeding for loop (code not shown). 这里的架子索引是当前架子的索引,我在前面有一个for循环(代码未显示)找到。
It's not working (the program won't even start up). 它不起作用(该程序甚至无法启动)。 I get the following error:
我收到以下错误:
SyntaxError: Unexpected token [
My shelves array is set up like: 我的书架阵列设置如下:
[{"racks":[],"shelfname":"Shelf 1"},{"racks":[],"shelfname":"Shelf 2"},{"racks":[],"shelfname":"Shelf 3"}]
So for instance if I was trying to push rack data to "Shelf 1" I am attempting to push it to: 因此,例如,如果我尝试将机架数据推送到“架子1”,则尝试将其推送到:
shelves[0].racks
Any ideas for a solution? 有解决方案的想法吗?
Would have been a little bit helpful if you had shown your Freezer model schema. 如果您展示了Freezer模型架构,将会有所帮助。 Nonetheless the following example is based on the sample data (example):
但是,以下示例基于示例数据(示例):
{
"_id" : ObjectId("565236570f7f257d5feffa10"),
"shelves" : [
{
"racks" : [],
"shelfname" : "Shelf 1"
},
{
"racks" : [],
"shelfname" : "Shelf 2"
},
{
"racks" : [],
"shelfname" : "Shelf 3"
}
]
}
So, pushing rack data to "Shelf 1"
shelf in mongo shell would use the positional $
operator which only supports one level deep and only the first matching element in its update. 因此,将机架数据推入mongo shell的
"Shelf 1"
机架将使用positional $
运算符,该运算符仅支持一个级别的深度,并且仅支持其更新中的第一个匹配元素。 Note, the shelves
array field must appear as part of the query document, hence { "shelves.shelfname": "Shelf 1" }
: 注意,
shelves
阵列字段必须出现在查询文档的一部分,因此, { "shelves.shelfname": "Shelf 1" }
db.freezer.update(
{ "shelves.shelfname": "Shelf 1" },
{
"$push": {
"shelves.$.racks": {
"rackname": 1,
"columns": 3,
"rows": 2,
"spaces" : []
}
}
}
);
Now, if you knew the specific array index then create the update document using the bracket notation : 现在,如果您知道特定的数组索引,则使用括号表示法创建更新文档:
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);
In your node.js, this would be similar but with a callback: 在您的node.js中,这将类似于但具有回调:
Freezer.update(conditions, update, function (err, doc){
console.log(doc);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.