findById() is not working properly

FindById() is not working and giving null.
Where as find(), findOne() works seamlessly.
I tried many many solutions to make findById() work. But, none of them worked.
One hack solution is to add _id in the schema. But this creates other problems in update and insert queries.

Please help me I am unable to proceed.

Please post your code and a screenshot of the error here.

I am actually having the same issue as the OP.

async function updateCourse(id) {

const course = await Course.findById(id)

if(!course) return 

course.isPublished = true = 'Another Author'

const result = await




So I found in another post that adding, ‘_id: String,’ to the Schema is the solution. It does work! However, if anyone sees this and it is the wrong approach please let me know the correct way.
Thank you.

add _id in the schema is never a legitimate solution… never do that… there is no reason why it won’t work. Can you use console.log to check where in the async function it stops running and what is the error message…

So from what I can tell, findById(), doesn’t work on strings if the ID is set to a string in the database. And for some reason the JSON information that I imported to mongoose, the _id’s are all strings.

I have the exact same problem. findById returns null. What is the final resolution? Please update. Thanks.

So what I did was delete the _id property in the JSON that Mosh had us import. If you do that then MongoDb sets the _id property automatically and then you’re able to use the findById()

Hey, hope you are doing fine.
So you did right by deleting _id from the JSON file, but you can also do this to convert that “_id: String” type to “ObjectId”

modify your JSON and for each document, change _id for instance:
_id: “5a68fde3f09ad7646ddec17e” to the following :

"_id": { "$oid": "5a68fde3f09ad7646ddec17e" }

and run mongoimport again.
This will import you JSON and convert all _id to objected type and not string type
Hope this will help you :slight_smile:

1 Like