[英]Node js, Mongoose $and not working
我想找到一個姓和名匹配的用戶。
router.post('/post/user/search/tag', function (req, res) {
function getRegex(_query) {
return {
$regex: '^' + _query + '|.*' + _query,
$options: "i",
};
}
var query = {};
query.$and = [];
_.map(req.body.params, function(_obj){
query.$and[v.type] = getRegex(v.name);
});
User.find(query).exec(function (err, docs) {
res.json({err: false, data: docs});
});
});
該API的示例輸入為:
{"params":
[
{
"name":"suresh",
"type":"first_name"
},
{
"name":"pattu",
"type":"last_name"
}
]
}
我從貓鼬得到的錯誤是:
undefined { MongoError: $and/$or/$nor must be a nonempty array
at Function.MongoError.create (/Users/user/code/project/trainer-ville-admin/node_modules/mongodb-core/lib/error.js:31:11)
at queryCallback (/Users/user/code/project/trainer-ville-admin/node_modules/mongodb-core/lib/cursor.js:212:36)
at /Users/user/code/project/trainer-ville-admin/node_modules/mongodb-core/lib/connection/pool.js:469:18
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)
name: 'MongoError',
message: '$and/$or/$nor must be a nonempty array',
ok: 0,
errmsg: '$and/$or/$nor must be a nonempty array',
code: 2, codeName: 'BadValue' }
在貓鼬查找查詢上解析的輸入是:
{ '$and':
[ first_name:{ '$regex': '^suresh|.*suresh', '$options': 'i' },
last_name:{ '$regex': '^pattu|.*pattu', '$options': 'i' }
]
}
實際上,您不需要$and
因為所有 MongoDB查詢參數已經是AND條件:
改為這樣做:
var input = {
"params" : [
{
"name" : "suresh",
"type" : "first_name"
},
{
"name" : "pattu",
"type" : "last_name"
}
]
};
var query = { };
input.params.forEach(p => {
query[p.type] = new RegExp('^'+ p.name + '|.*' + p.name, 'i');
})
query
的輸出如下所示:
{ "first_name" : /^suresh|.*suresh/i, "last_name" : /^pattu|.*pattu/i }
當然,這是您想要的完全有效的語句。
您的問題是這樣的:
_.map(function(_obj){
query.$and[v.type] = getRegex(v.name);
});
您正在調用_.map
,它會遍歷一個集合,但是那里沒有任何集合。 它看起來應該像這樣:
_.map(someCollection, function(_obj) {
query.$and[v.type] = getRegex(v.name);
});
您沒有遍歷代碼中的任何內容,因此query.$and[v.type] = getRegex(v.name);
永遠不會執行,因此您的$ and數組為空。
另外,我看不到您的代碼段中定義了v
位置。
以下是有關_.map
工作方式以及接收的參數的有用鏈接:
希望這會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.