通过电话号码进行猫鼬用户批量搜索

时间:2017-02-20 15:35:35

标签: node.js mongodb mongoose mongodb-query aggregation-framework

我有UserSchema,其中包含PhoneNumberSchema,如下所示。

var PhoneNumberSchema = new Schema({
    country: {
        type: String
    },
    country_code: {
        type: Number
    },
    local_number: {
        type: Number
    }
});

这是phone_number的示例json格式。

"phone_number": {
    "country": "US",
    "country_code": "1",
    "local_number": "04152341"
}

我想要做的是通过带/不带国家/地区代码的电话号码搜索用户。

好吧,如果请求是

  

“phone_numbers”:[“104152341”,“124254364”]

然后我想让那些拥有完全匹配的电话号码的用户属于请求电话号码数组,包含/不包含国家/地区代码。

所以,我尝试如下,但错误“无效运算符'$ in'”。

User.aggregate(
    [   
        { "$redact": { 
            "$cond": [ 
                { 
                    "$in": [ { "$concat": [ "$phone_number.country_code", "$phone_number.local_number" ] }, req.body.phone_numbers]
                },
                "$$KEEP",
                "$$PRUNE"
            ]
        }}
    ],
    function(err, users) {
        // Do something
        if (err) {
            return res.json({ success: false, err: err });
        }
        res.json({ success: true, users: users });
    }
)

我希望知道如何处理我的问题。

请帮助我!!

1 个答案:

答案 0 :(得分:0)

使用 $setIsSubset 作为条件表达式:

{ "$redact": { 
    "$cond": [ 
        { 
            "$setIsSubset": [ 
                [ 
                    { 
                        "$concat": [ 
                            "$phone_number.country_code", 
                            "$phone_number.local_number" 
                        ] 
                    } 
                ], 
                req.body.phone_numbers 
            ]
        },
        "$$KEEP",
        "$$PRUNE"
    ]
}}