猫鼬找到文档内的任何地方

时间:2014-10-07 06:38:29

标签: node.js mongodb mongoose underscore.js

我需要找到匹配userId的记录。 userId可以在任何级别的文档中。 它可以在父级别,也可以在friends数组中。

[{
    "_id": "543357620c9af6066e689713",
    "createdDate": "2014-10-06 08:00 pm",
    "cancle": false,
    "eventDate": "2014/12/12",
    "eventstatus": true,
    "location": "chennai",
    "userId": "54334def7e85de48638d1069",
    "createdBy": "four",
    "eventName": "jamba",
    "__v": 0,
    "friends": []
},
{
    "_id": "543356fe0c9af6066e68970c",
    "createdDate": "2014-10-06 07:59 pm",
    "cancle": false,
    "eventDate": "2014/12/12",
    "eventstatus": true,
    "location": "chennai",
    "userId": "54310801e2659ecc3650100b",
    "createdBy": "one",
    "eventName": "tea ",
    "__v": 0,
    "friends": [
        {
            "userId": "54310814e2659ecc3650100c",
            "userName": "two",
            "phoneNumber": "22222222"
        },
        {
            "userId": "54310945e2659ecc3650100d",
            "userName": "three",
            "phoneNumber": "33333333"
        },
        {
            "userId": "54334def7e85de48638d1069",
            "userName": "four",
            "phoneNumber": "44444444"
        }
    ]
}]

我很长时间都在努力。任何帮助都非常感谢。

1 个答案:

答案 0 :(得分:0)

您需要$or运算符。此外,您不需要迭代来查询数组中的元素。假设您的收藏名为Events

Events.find({
    $or: [
        { _id: req.params.userId },
        { 'friends.userId': req.params.userId }
    ]
}).exec();