0

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.

Joshua Majebi
  • 1,110
  • 4
  • 16
  • 34
  • I wouldn't expect the last snippet to work. You're giving it a string and not an ObjectId – Taplar May 18 '20 at 20:25
  • But what is the problem with the code not working when it was working before. Id queries on the User collection worked – Joshua Majebi May 18 '20 at 20:29
  • 1
    Dunno. In my experience I've never thought to try to match an ObjectId field to a string. I wouldn't have expected it to ever work. – Taplar May 18 '20 at 20:32
  • Does this answer your question? [Node.js Mongoose.js string to ObjectId function](https://stackoverflow.com/questions/6578178/node-js-mongoose-js-string-to-objectid-function) Issue is you need to convert it to the type which is in DB in order to match (Here `_id` is of type `ObjectId()` so use above link to convert & then query DB) – whoami - fakeFaceTrueSoul May 18 '20 at 20:53

1 Answers1

0

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 (i.e. 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)?

eol
  • 23,236
  • 5
  • 46
  • 64