如何在具有匹配内部值的Mongoose文档中选择内部对象?

时间:2016-01-27 05:49:48

标签: node.js mongodb express mongoose

我对Mongoose有些新手并且不熟悉更复杂的查询,但实质上我正在尝试选择具有两个匹配内部值的所有内部对象。

我正在尝试选择所有已经回复的内部消息对象(向同一个人发送和接收)。例如,请注意“to”和“from”值如何匹配:

{
    "_id" : ObjectId("567f225438dh626f3f0d2767"),
    "messages" : {
        "sent": [
            { "to": "Bob", ... }
        ],
        "received": [
            { "from": "Bob", ... }
        ],
        ....
    },
    ....
}

因此,我希望返回{ "from": "Bob", ... }内部对象,以及所有其他已接收的消息,这些消息具有相应的匹配“发送到”值。我该如何处理这种查询?

1 个答案:

答案 0 :(得分:0)

我的解决方案使用简单的嵌套for循环:

var received = user.messages.received || [],
    receivedCount = received.length,
    sent = user.messages.sent || [],
    sentCount = sent.length,
    results = [];

for (var r = 0; r < receivedCount; r++) {
    for (var s = 0; s < sentCount; s++) {
        if (sent[s] && sent[s].to &&
            received[s] && received[s].from &&
            sent[s].to === received[r].from) {
                results.push(received[s]);
        }
    }
}