简体   繁体   中英

Mongoose find query result always a null object

I'm desperately trying to solve my problem with "find" queries with mongoose in my app.

I begin to know very well the middleware, I used it on others apps and work well, but on a new project something goes wrong and it only finds null objects in my database...

//server/app.js
var db = require('./lib/database');
var User = require('./models/user'); 

//server/lib/database.js
var mongoose = require('mongoose');
var db = function () {
     mongoose.connect('mongodb://localhost/pipeline');
     var connection = mongoose.connection;
     connection.on('error', console.error.bind(console, 'connection error'));
     connection.once('open', function callback() { 
         console.log('connected');                 //result : connected
     });
};
module.exports = db();

//server/models/user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({ username: String, password: String });
module.exports = mongoose.model('User', userSchema);

Mongoose is well connected, there's no error in the console. So when mongoose is connected I use this method (I precisely use this in my LocalStrategy for PassportJS) :

User.findOne({username: "Paul"}, function (err, user){
    console.log(user);                                // result : null
});

It's always null (and no error during the query), I also tested find({}) to check all entries, but the result is an empty array [] .

Here's the User collection of my pipeline database (checked with Robomongo):

/* 0 */
{
    "_id" : ObjectId("547649df8d99c22fa995b050"),
    "username" : "Paul",
    "password" : "test"
}

/* 1 */
{
    "_id" : ObjectId("54765efdcd3b13c80c2d03e2"),
    "username" : "Micka",
    "password" : "lol"
}

Thank you for your help.

要让'User'模型使用User集合,您需要显式提供该集合名称作为mongoose.model的第三个参数,否则Mongoose将使用复数的小写模型名称,它们将是users

module.exports = mongoose.model('User', userSchema, 'User');

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