【问题标题】:Inserting array into array with mongoose使用猫鼬将数组插入数组
【发布时间】:2016-03-05 22:53:34
【问题描述】:

我在使用 Mongoose 插入嵌套数组时遇到问题。

我正在尝试将 AP 插入到网络数组中特定网络内的 APList 数组中。

我一直在尝试使用:

var ap = {
    MAC      : req.body.APMAC,
    location : req.body.location
}
var query = {
    name            : req.decoded.name,
    'networks.ssid' : req.body.ssid
}

User.update(query, 
            {$push: {'APList' : ap}},
            {safe: true, upsert: true, new: true},
            function(err, data) {
                res.json({
                    success: true,
                    message: "Added AP"
                })
            })

req.decoded.name 来自 JWT,发送的正文参数为 APMAC、位置和 ssid。

这总是以成功的“已添加 AP”消息登陆,但尚未更新 APList 数组以包含在 POST 请求中发送的 AP。

【问题讨论】:

    标签: arrays node.js mongodb mongoose


    【解决方案1】:

    在您的更新中应用$push 运算符和$ positional operator 以将ap 对象添加到嵌入的APList 字段。

    $ positional operator 将为您识别 networks 数组中要更新的正确元素,而无需明确指定其在数组中的位置,因此您的最终更新语句应如下所示:

    User.update(query,
        { "$push": { "networks.$.APList": ap } },
        { "upsert": true, "new": true },
        function(err, data) {
            res.json({
                success: true,
                message: "Added AP",
                data: data
            });
        }
    );
    

    【讨论】:

    • 不幸的是,这仍然没有奏效。我得到的数据是:{ "success": true, "message": "Added AP", "data": { "ok": 0, "n": 0, "nModified": 0 } }
    • 检查你的查询,使用一些带有 mongo shell 的示例文档作为调试提示进行测试。
    猜你喜欢
    • 2022-01-07
    • 2017-02-25
    • 2017-08-14
    • 2017-04-18
    • 2019-06-09
    • 2016-11-05
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    相关资源
    最近更新 更多