Arrays 如何使用nodejs中的mongoose将值推送到特定的数组索引?

Arrays 如何使用nodejs中的mongoose将值推送到特定的数组索引?,arrays,node.js,mongodb,mongoose,Arrays,Node.js,Mongodb,Mongoose,我尝试使用以下代码将值推送到数组特定索引处的数组: Freezer.update(conditions, {$push: {shelves[shelfindex] : {"rackname": rackname, "columns": columns, "rows": rows, "spaces" : []}}}, function (err, doc){ console.log(doc); }) 其中shelfindex是手头工具架的索引,我使用前面的f

我尝试使用以下代码将值推送到数组特定索引处的数组:

Freezer.update(conditions, {$push: {shelves[shelfindex] : {"rackname": rackname, "columns": columns, "rows": rows, "spaces" : []}}}, function (err, doc){

          console.log(doc);
        })
其中shelfindex是手头工具架的索引,我使用前面的for循环找到它(代码未显示)

它不起作用(程序甚至无法启动)。我得到以下错误:

SyntaxError: Unexpected token [
我的书架阵列设置如下:

[{"racks":[],"shelfname":"Shelf 1"},{"racks":[],"shelfname":"Shelf 2"},{"racks":[],"shelfname":"Shelf 3"}]
因此,例如,如果我试图将机架数据推送到“托架1”,我将尝试将其推送到:

shelves[0].racks

有什么解决方案吗?

如果您展示了您的冷冻柜模型模式,可能会有点帮助。尽管如此,以下示例基于样本数据(示例):

因此,将机架数据推送到mongo shell中的
“Shelf 1”
Shelf将使用操作符,该操作符只支持一级深度,并且在其更新中只支持第一个匹配元素。注意,
shelfs
数组字段必须作为查询文档的一部分出现,因此
{“shelfs.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);
});

如果您展示了您的冷冻柜模型模式,将会有一点帮助。尽管如此,以下示例基于样本数据(示例):

因此,将机架数据推送到mongo shell中的
“Shelf 1”
Shelf将使用操作符,该操作符只支持一级深度,并且在其更新中只支持第一个匹配元素。注意,
shelfs
数组字段必须作为查询文档的一部分出现,因此
{“shelfs.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);
});