【问题标题】:How can I push a value to a specific array index using mongoose in nodejs?如何在 nodejs 中使用 mongoose 将值推送到特定的数组索引?
【发布时间】:2016-02-24 22:11:22
【问题描述】:

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

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

有解决方案的想法吗?

【问题讨论】:

    标签: arrays node.js mongodb mongoose


    【解决方案1】:

    如果您展示了您的 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" : []       
                }
            }
        }
    );
    

    现在,如果您知道具体的数组索引,然后使用 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);
    

    在你的 node.js 中,这将是相似的,但有一个回调:

    Freezer.update(conditions, update, function (err, doc){
        console.log(doc);
    });
    

    【讨论】:

      猜你喜欢
      • 2019-04-16
      • 2021-12-27
      • 2021-02-16
      • 2019-11-19
      • 1970-01-01
      • 2021-11-08
      • 2014-12-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多