简体   繁体   中英

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.

All of a sudden when I am trying to read the collection via id it returns 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

 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 -

 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.

You need to convert the id to an ObjectId, which can be simply done with:

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)?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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