简体   繁体   中英

How to perform findOne query in mongoose

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:

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.

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM