我正在尝试根据针对待办事项存储的“userId”来获取待办事项列表。使用以下代码不会返回任何行。
DB.TodoTable.find({ "userId" : ObjectId("54c12f5f3620c07019e6b144") }, function(err, todos) {
if (err) return console.error(err);
console.dir(todos);
})
Mongoose 调试给出:
Mongoose: todos.find({ userId: undefined }) { fields: undefined }
[]
但是当我在 mongo shell 中尝试相同的操作时,它起作用了。如下:
> db.todos.find()
{ "_id" : ObjectId("54c12f643620c07019e6b145"), "created_at" : ISODate("2015-01-22T17:12:04.932Z"), "userId" : ObjectId(
"54c12f5f3620c07019e6b144"), "text" : "data", "__v" : 0 }
我的数据库架构如下:
var TodoTable = mongoose.model('todos', {
text : {type : String, default: ''},
created_at : Date,
userId : {type:ObjectId, ref:'users'}
});
var UserTable = mongoose.model('users', {
username: String,
password: String,
email: String,
gender: String,
address: String
});
最佳答案
令人困惑的是,mongoose.Schema.ObjectId
不是 ObjectID
构造函数,它仅用于定义架构。
但是您无论如何都不需要从该字符串创建 ObjectID,因为 Mongoose 会根据架构定义为您执行此操作,因此您可以简单地使用:
DB.TodoTable.find({ "userId": "54c12f5f3620c07019e6b144" }, function(err, todos) {...})
或者,如果您处于需要明确的情况,您可以访问 ObjectID
构造函数:
DB.TodoTable.find({ "userId": mongoose.mongo.ObjectID("54c12f5f3620c07019e6b144") },
function(err, todos) {...})
关于node.js - mongoose 查询在 Node.js 中不起作用,但在 mongo shell 中起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28095304/