mongoose从嵌套数组

时间:2018-02-06 09:58:16

标签: javascript node.js mongodb mongoose

我试图通过从嵌套数组中删除对象来使用mongoose查找文档更新。我的目标文件如下:

user = {
    "userId" : "myId",
    "connections":
    [{
        "dateConnectedUnix": 1334567891,
        "isActive": true,
        "sessions": [
            {"device": "mobile", "country": "US"},
            {"device": "desktop", "country": "US"}
        ]
    }, {
        "dateConnectedUnix": 1334567893,
        "isActive": false,
        "sessions": [
            {"device": "mobile", "country": "CA"},
            {"device": "desktop", "country": "CA"}
        ]
    }]
}

这是我的尝试,但它没有更新文档:

Users.findOneAndUpdate({ "userId": "myId", "connections.dateConnectedUnix": 1334567891 },
    { $pull: { sessions: { device: "mobile" } } }, (err) => {
        if (err) {
            return res.status(404).json({ message: 'Error' });
        }
        return res.status(200).json({
            success: true,
            message: 'success'
        });
    }
);

生成的文档应如下所示:

user = {
    "userId" : "myId",
    "connections":
    [{
        "dateConnectedUnix": 1334567891,
        "isActive": true,
        "sessions": [
            {"device": "desktop", "country": "US"}
        ]
    }, {
        "dateConnectedUnix": 1334567893,
        "isActive": false,
        "sessions": [
            {"device": "mobile", "country": "CA"},
            {"device": "desktop", "country": "CA"}
        ]
    }]
}

基本上它是通过id找到用户,然后按日期查找连接,然后移动设备。在我的特定情况下,结果总是一个匹配的文档和一个匹配的连接和一个匹配的会话。

2 个答案:

答案 0 :(得分:2)

因为会话数组在连接内部

尝试"连接。$。sessions"而不是会话,所以你的查询将是

Users.findOneAndUpdate({ "userId": "myId", "connections.dateConnectedUnix": 1334567891 },
    { $pull: { "connections.$.sessions" : { device: "mobile" } } }, (err) => {
        if (err) {
            return res.status(404).json({ message: 'Error' });
        }
        return res.status(200).json({
            success: true,
            message: 'success'
        });
    }
);

答案 1 :(得分:-1)

Users.findOneAndUpdate({ _id: "myId" }, { $pull: { connections.sessions: { device: "mobile" } } }, { new: true });