【问题标题】:Mongoose find query result always a null objectMongoose 查找查询结果始终为空对象
【发布时间】:2015-01-25 11:56:12
【问题描述】:

我正在拼命尝试通过在我的应用中使用猫鼬“查找”查询来解决我的问题。

我开始非常了解中间件,我在其他应用程序上使用它并且运行良好,但在一个新项目中出现问题,它只能在我的数据库中找到空对象...

//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 连接良好,控制台没有错误。所以当猫鼬连接时我使用这个方法(我在我的 LocalStrategy for PassportJS 中精确地使用了这个):

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

它始终为空(并且在查询过程中没有错误),我还测试了find({}) 以检查所有条目,但结果是一个空数组[]

这是我的管道数据库的用户集合(使用 Robomongo 检查):

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

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

感谢您的帮助。

【问题讨论】:

  • 检查是否连接到正确的数据库。
  • 是的,我是。我的数据库是 mongodb://localhost:27017/pipeline,我测试了在地址中添加端口但没有改变任何东西。

标签: node.js mongoose passport.js


【解决方案1】:

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

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

【讨论】:

  • 简单到我自己都看不到..谢谢!最后,我认为我的旧应用程序很幸运,因为我在数据库中使用了复数名称。 ^^
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-22
  • 2020-04-08
  • 1970-01-01
  • 1970-01-01
  • 2015-05-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多