node.js 如何在猫鼬中执行 findOne 查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12818051/
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-09-02 16:27:44  来源:igfitidea点击:

How to perform findOne query in mongoose

node.jsmongodbmongoose

提问by Mohamed Challouf

i have mongoose schema named administrator

我有名为管理员的猫鼬模式

var administratorSchema = new mongoose.Schema({

username : String,            
password : String,
    active : Boolean,
    level : String
});

When i try this query,i can get the result

当我尝试这个查询时,我可以得到结果

mongoose.connect('mongodb://'+dbServer+'/'+dbName, function(connectionError) {
        var administratorModel = mongoose.model('administrators',administratorSchema);
        administratorModel.findOne({_id,111155dffxv}function(err, resad){
            console.log('into mongoose findone');
        });
});
====> Console output : 'into mongoose findone'

The problem is : when i try to change the criteria from _id to "username", mongoose dosen't work and findOne dosen't execute:

问题是:当我尝试将标准从 _id 更改为“用户名”时,猫鼬不起作用并且 findOne 不执行:

mongoose.connect('mongodb://'+dbServer+'/'+dbName, function(connectionError) {
        var administratorModel = mongoose.model('administrators',administratorSchema);
        administratorModel.findOne({'username','mohamed'}function(err, resad){
            console.log('into mongoose findone');
        });
});
====> Console output : ''

Thanks.

谢谢。

回答by JohnnyHK

Your query object isn't valid (use a colon instead of a comma) and you're missing a comma between the findOneparameters. Your call should look like this instead:

您的查询对象无效(使用冒号而不是逗号)并且您在findOne参数之间缺少逗号。你的电话应该是这样的:

administratorModel.findOne({'username': 'mohamed'}, function(err, resad){
     console.log('into mongoose findone');
});

You should also be checking the errparameter of your callbacks to see if things are working.

您还应该检查err回调的参数以查看是否正常。

Not sure why it was reaching the callback with your _idcriteria version as that one has the same issues.

不知道为什么它会使用您的_id标准版本进行回调,因为该版本具有相同的问题。