Mongoose 的 $or 条件查找方法无法正常工作 [英] Mongoose's find method with $or condition does not work properly
本文介绍了Mongoose 的 $or 条件查找方法无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
最近我开始在 Nodejs 上使用 MongoDB 和 Mongoose.
Recently I start using MongoDB with Mongoose on Nodejs.
当我使用带有 $or
条件和 _id
字段的 Model.find 方法时,Mongoose 无法正常工作.
When I use Model.find method with $or
condition and _id
field, Mongoose does not work properly.
这不起作用:
User.find({
$or: [
{ '_id': param },
{ 'name': param },
{ 'nickname': param }
]
}, function(err, docs) {
if(!err) res.send(docs);
});
顺便说一句,如果我删除_id"部分,这确实有效!
By the way, if I remove the '_id' part, this DOES work!
User.find({
$or: [
{ 'name': param },
{ 'nickname': param }
]
}, function(err, docs) {
if(!err) res.send(docs);
});
在 MongoDB shell 中,两者都可以正常工作.
And in MongoDB shell, both work properly.
推荐答案
我通过谷歌搜索解决了:
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);
});
这篇关于Mongoose 的 $or 条件查找方法无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文