简体   繁体   English

在 mongodb 的读取查询中无法识别集合 ID

[英]collection id not recognised in read query in mongodb

I have a mongoDB on an ec2 instance, I have been able to query a collection called Users successfully.我在 ec2 实例上有一个 mongoDB,我已经能够成功查询一个名为 Users 的集合。

All of a sudden when I am trying to read the collection via id it returns null.突然间,当我试图通过 id 读取集合时,它返回 null。

I logged into the instance and queried the database for users and there exists some orders.我登录到实例并查询数据库中的用户,并且存在一些订单。

I am using mongoose with the following query in my code我在我的代码中使用 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) }) }) }

When querying from the shell i use the following, and it works -从 shell 查询时,我使用以下内容,它可以工作 -

 db.users.find({_id: ObjectId("5e89be482845434a7da45863")})

The above code should work once I am passing in a valid ObjectId String, but it fails across other collections as well.一旦我传入一个有效的 ObjectId 字符串,上面的代码应该可以工作,但它也会在其他 collections 中失败。

You need to convert the id to an ObjectId, which can be simply done with:您需要将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)
            })
    })
}

To answer why it worked before without using ObjectId ... Maybe you changed how new entries are added (ie maybe you had manually set the _id to a string before, but now you don't and the _id is now set automatically, which is an ObjectId by default)?要回答为什么它以前不使用ObjectId就可以工作...也许您更改了添加新条目的方式(即,您之前可能已经手动将_id设置为字符串,但现在您没有,并且_id现在是自动设置的,即默认情况下为 ObjectId)?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM