首页 文章

Mongoose查询findOne({params})返回null,即使它在mongo shell中成功了吗?

提问于
浏览
1

以下是使用中的软件版本:

  • mongoose 4.10.8,

  • mongodb 3.4,

  • express 4.13.4,

  • nodejs 6.11.1,

  • npm 3.10.10,

在Mongo shell中,我可以找到一个没有问题的用户:

> db.users.findOne({"admin":"true"}).pretty()

>{
        "_id" : ObjectId("..."),
        "updatedAt" : ISODate("2017-08-15T06:08:24.742Z"),
        "createdAt" : ISODate("2017-08-03T03:11:23.653Z"),
        "salt" : "...",
        "hash" : "...",
        "username" : "Testuser",
        "notifications" : [
                {
                }
        ],
        "lastname" : "Administrator",
        "firstname" : "Webmaster",
        //********* FIELD I AM SEARCHING FOR HERE!
        "admin" : "true",
        "companyName" : "",
        "__v" : 11,
        "company" : ObjectId("59868130522b9a0fe05808c7")
}
>

在我的一个路由器中,我尝试 grab 这个用户:

>Users.findOne({"admin":"true"}, "username", function (err, admin) { do stuff here});

引用http://mongoosejs.com/docs/queries.html

我已经尝试了查询的所有可能变体 . 从删除引号到只是{admin:true},再到使用find({admin:true})而不是findOne ..但无论我尝试什么,它都拒绝返回除null之外的任何内容 . 我已经尝试将其作为查询并调用exec而不是传递回调函数 .

在不同的用途中,我做Users.findById并得到结果没问题 . 所以我知道访问数据库或模式问题不是问题 . 我甚至使用没有搜索参数的findOne,并且能够找到我的用户(这是数据库中的第一个) . 我疯了 . 有没有人有什么建议?我只是不知道我还能尝试什么......

user.js架构供参考..

var mongoose                = require('mongoose');
var Schema                  = mongoose.Schema;
var passportLocalMongoose   = require('passport-local-mongoose');

var Notification = new Schema({
    body: {type: String, default: ''}
}, {timestamps:true});


var User = new Schema({

    //Is this user an admin? 
    admin: {type: Boolean, default: false},
    firstname: { type: String, default: ''},
    lastname: { type: String, default: ''},
    //Array of all the notifications for this user
    notifications: [Notification]

}, {timestamps: true});


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

1 回答

  • 1

    答案,由Neil Lunn提供......实际存储在我的数据库中的数据是{"admin":"true"} ...其中admin字段是字符串值 . 现在,在我的mongoose模式中,我将该字段设置为布尔值,所以当我去查找({"admin":"true"})时,它会自动将"true"字符串值转换为真正的布尔值,因此永远不会找到匹配因为"true" !=真的 . 出现此问题是因为我使用mongodb shell手动将该字段设置为"true";所以我可以创建一个管理员用户 . 默认情况下,根据我的架构使用Mongoose,将该值设置为false .

相关问题