gpt4 book ai didi

node.js - mongoose 查询在 node.js 中不起作用,但在 mongo shell 中有效

转载 作者:可可西里 更新时间:2023-11-01 10:00:46 27 4
gpt4 key购买 nike

我正在尝试根据针对待办事项存储的“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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com