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.
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.
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
This is the answer. For anyone who didn’t understand, go back to lesson 7.14 and download the JSON that contains the data for the mongose db. Mosh made a mistake with his formatting that you will need to fix.
Change each line to have each _id as an object with a key of $oid. Example:
{"_id": { “$oid”: “5a68fdc3615eda645bc6bdec”}…
Once you have done that. Save the JSON file, then run the important command again in that folder, the same you did in the 7.14 exercise.