以下是正在使用的软件版本:
- Mongoose 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);
最佳答案
答案,由 Neil Lunn 提供...实际存储在我的数据库中的数据是 {"admin":"true"} ...其中 admin 字段是一个字符串值。现在,在我的 Mongoose 模式中,我将该字段设置为 bool 值,所以当我去查找({“admin”:“true”})时,它会自动将“true”字符串值转换为真正的 bool 值,因此永远找不到匹配项,因为“true”!= true。发生这个问题是因为我使用 mongodb shell 手动将该字段设置为“true”;所以我可以创建一个管理员用户。默认情况下,根据我的架构, Mongoose 将该值设置为 false。
关于javascript - Mongoose 查询 findOne({params}) 返回 null,即使它在 mongo shell 中成功?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45705192/