【问题标题】:Mongoose query findOne({params}) returns null, even though it succeeds in mongo shell?猫鼬查询 findOne({params}) 返回 null,即使它在 mongo shell 中成功?
【发布时间】:2017-08-16 22:53:46
【问题描述】:

以下是正在使用的软件版本:

  • 猫鼬 4.10.8,
  • mongodb 3.4,
  • 表达 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")
}
>

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

>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);

【问题讨论】:

  • admin: {type: Boolean, default: false}, 对于存储的数据实际上是不正确的。数据实际上存储为“字符串”。因此,要么修复您的数据,要么将您的架构更正为 admin: String。 Mongoose 将查询中提供的“字符串”强制为boolean,这当然与集合中的数据不匹配。
  • 我现在有很多矛盾的情绪。祝福你的心尼尔。这确实是问题所在,当然是自己造成的。我已经从 mongodb shell 手动将该字段设置为“true”......没有完全有意识地了解可以存储在 mongo 中的不同类型的变量。我只是有点愚蠢地忽略了它,并认为这是一个格式化交易。反正。哇,你是另一个随机互联网人的英雄。再次非常感谢您的回复。现在要弄清楚如何将其标记为正确答案....
  • @user6641203:您需要提示 neil 将他的评论添加为答案,以便您可以将其标记为已接受。如果他没有在合理的时间范围内这样做,我会自己将其添加为答案并将其标记为已接受。

标签: javascript node.js mongodb mongoose


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2019-03-25
    • 1970-01-01
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    • 2012-09-30
    • 1970-01-01
    • 2020-02-03
    • 2017-07-22
    相关资源
    最近更新 更多