Javascript 如何在 Mongoose 中执行查询?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5813979/
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
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:01:37 来源:igfitidea点击:
How do I perform a query in Mongoose?
提问by TIMEX
> db.users.findOne();
{
"_id" : ObjectId("4db8ebb4c693ec0363000001"),
"fb" : {
"name" : {
"last" : "Sss",
"first" : "Fss",
"full" : "Fss"
},
"updatedTime" : "2011-04-27T09:51:01+0000",
"verified" : true,
"locale" : "en_US",
"timezone" : "-7",
"email" : "[email protected]",
"gender" : "male",
"alias" : "abc",
"id" : "17447214"
}
}
So that's my Mongo object. Now i want to find it via Mongoose:
这就是我的 Mongo 对象。现在我想通过猫鼬找到它:
User.findOne( { gender: "male" }, function(err, docs){
console.log(err); //returns Null
console.log(docs); //returns Null.
});
That doesn't work! Neither does this:
那不行!这也不行:
User.findOne( { fb: {gender:"male"} }, function...
Null, null.
空,空。
This is my entire thing:
这是我的全部内容:
app.get('/:uid',function(req,res){
params = {}
User.findOne({ $where : "this.fb.gender == 'male' " }, function(err, docs){
console.log(docs);
});
res.render('user', { locals:params });
});
采纳答案by DhruvPathak
Try this :
尝试这个 :
User.findOne( { $where : "this.fb.gender == 'male' " } )
or
或者
User.findOne( { fb.gender : "male" } )
回答by Brian Noguchi
I'm one of the authors of mongoose. You can do this query in one of several ways:
我是猫鼬的作者之一。您可以通过以下几种方式之一执行此查询:
find
syntaxUser.findOne({'fb.gender': 'male'}, callback);
where
syntaxUser.where('fb.gender', 'male').findOne(callback);
named scope syntax
UserSchema.namedscope('male').where('fb.gender', 'male'); // ... var User = mongoose.model('User', UserSchema); // Now you can write queries even more succinctly and idiomatically User.male.findOne(callback);
find
句法User.findOne({'fb.gender': 'male'}, callback);
where
句法User.where('fb.gender', 'male').findOne(callback);
命名范围语法
UserSchema.namedscope('male').where('fb.gender', 'male'); // ... var User = mongoose.model('User', UserSchema); // Now you can write queries even more succinctly and idiomatically User.male.findOne(callback);