使用mongoose

时间:2016-03-05 14:46:36

标签: arrays node.js mongodb mongoose

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

我正在尝试将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,location& SSID。

这总是取得成功"增加了AP"消息,但尚未更新APList阵列以包括在POST请求中发送的AP。

1 个答案:

答案 0 :(得分:0)

$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
        });
    }
);
相关问题