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

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

  • mongoose4.10.8,
  • mongodb 3.4,
  • expression4.13.4,
  • nodejs 6.11.1,
  • npm 3.10.10,

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

> 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 ..但不pipe我尝试什么,它都拒绝返回任何东西,但是返回null。 我试图做一个查询和调用exec而不是传递一个callback函数。

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

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

回答,由Neil Lunn提供…实际存储在我的数据库中的数据是{“admin”:“true”} …其中admin字段是一个string值。 现在,在我的mongoose模式中,我将该字段设置为布尔值,所以当我去查找({“admin”:“true”})时,它会自动将该“true”string值转换为一个真正的布尔值从来没有find匹配,因为“真”!=真。 发生这个问题是因为我使用mongodb shell手动将该字段设置为“true” 所以我可以创build一个pipe理员用户。 Mongoose默认情况下,我的架构,将该值设置为false。