具有$ or条件的猫鼬的find方法无法正常工作 [英] Mongoose's find method with $or condition does not work properly
本文介绍了具有$ or条件的猫鼬的find方法无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
最近,我开始在Node.js上将MongoDB与Mongoose结合使用.
Recently I start using MongoDB with Mongoose on Nodejs.
当我在$or
条件和_id
字段中使用Model.find方法时,猫鼬无法正常工作.
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);
});
这篇关于具有$ or条件的猫鼬的find方法无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文