Mongoose query findOne({params}) 返回 null,即使它在 mongo shell 中成



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

  • 猫鼬 4.10.8,
  • 蒙戈德布 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,并且能够找到我的用户(这是数据库中的第一个(。我快疯了。有人有什么建议吗?我只是不知道我还能尝试什么....

用户.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);

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

最新更新