node.js Mongoose 的 $or 条件查找方法无法正常工作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7382207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mongoose's find method with $or condition does not work properly
提问by Younghan
Recently I start using MongoDB with Mongoose on Nodejs.
最近我开始在 Nodejs 上使用 MongoDB 和 Mongoose。
When I use Model.find method with $orcondition and _idfield, Mongoose does not work properly.
当我使用带有$or条件和_id字段的Model.find 方法时,Mongoose 无法正常工作。
This does not work:
这不起作用:
User.find({
$or: [
{ '_id': param },
{ 'name': param },
{ 'nickname': param }
]
}, function(err, docs) {
if(!err) res.send(docs);
});
By the way, if I remove the '_id' part, this DOES work!
顺便说一句,如果我删除“_id”部分,这确实有效!
User.find({
$or: [
{ 'name': param },
{ 'nickname': param }
]
}, function(err, docs) {
if(!err) res.send(docs);
});
And in MongoDB shell, both work properly.
在 MongoDB shell 中,两者都可以正常工作。
回答by Younghan
I solved it through googling:
我通过谷歌搜索解决了它:
var ObjectId = require('mongoose').Types.ObjectId;
var objId = new ObjectId( (param.length < 12) ? "123456789012" : param );
// You should make string 'param' as ObjectId type. To avoid exception,
// the 'param' must consist of more than 12 characters.
User.find( { $or:[ {'_id':objId}, {'name':param}, {'nickname':param} ]},
function(err,docs){
if(!err) res.send(docs);
});
回答by Govind Rai
I implore everyone to use Mongoose's query builder language and promises instead of callbacks:
我恳请大家使用 Mongoose 的查询构建器语言和承诺而不是回调:
User.find().or([{ name: param }, { nickname: param }])
.then(users => { /*logic here*/ })
.catch(error => { /*error logic here*/ })
Read more about Mongoose Queries.
阅读有关猫鼬查询的更多信息。
回答by Farasi78
According to mongoDB documentation: "...That is, for MongoDB to use indexes to evaluate an $or expression, all the clauses in the $or expression must be supported by indexes."
根据 mongoDB 文档:“...也就是说,对于 MongoDB 使用索引来评估 $or 表达式,$or 表达式中的所有子句都必须由索引支持。”
So add indexes for your other fields and it will work. I had a similar problem and this solved it.
因此,为您的其他字段添加索引,它将起作用。我有一个类似的问题,这解决了它。
You can read more here: https://docs.mongodb.com/manual/reference/operator/query/or/
您可以在此处阅读更多信息:https: //docs.mongodb.com/manual/reference/operator/query/or/

