[英]collection id not recognised in read query in mongodb
我在 ec2 实例上有一个 mongoDB,我已经能够成功查询一个名为 Users 的集合。
突然间,当我试图通过 id 读取集合时,它返回 null。
我登录到实例并查询数据库中的用户,并且存在一些订单。
我在我的代码中使用 mongoose 和以下查询
module.exports.readUser = function(id){ return new Promise((resolve,reject) => { User.findOne({_id: id}).exec().then(rem => { resolve(rem); }).catch(error => { reject(error.message) }) }) }
从 shell 查询时,我使用以下内容,它可以工作 -
db.users.find({_id: ObjectId("5e89be482845434a7da45863")})
一旦我传入一个有效的 ObjectId 字符串,上面的代码应该可以工作,但它也会在其他 collections 中失败。
您需要将id
转换为 ObjectId,这可以简单地完成:
const { ObjectId } = require('mongodb');
module.exports.readUser = function(id){
return new Promise((resolve,reject) => {
User.findOne({_id: ObjectId(id)})
.exec()
.then(rem => {
resolve(rem);
})
.catch(error => {
reject(error.message)
})
})
}
要回答为什么它以前不使用ObjectId
就可以工作...也许您更改了添加新条目的方式(即,您之前可能已经手动将_id
设置为字符串,但现在您没有,并且_id
现在是自动设置的,即默认情况下为 ObjectId)?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.