Mongoose findbyid() return null
I had the same problem. The _id in my DB collection was a String
. After I enabled mongoose debug require('mongoose').set('debug', true)
, I found out that the mongoose query id
as ObjectId("yourId")
unless we define _id
in the Schema. In order to solve the problem I had to add _id:String
in to mongoose schema.
const MyDataSchema = new Schema({
_id: String,
...
...
}
There is a simple solution to this:
Replace
const result = await Data.findById(id);
with
const result = await Data.findById(id).exec();
See Mongoose - What does the exec function do? for an explanation on what exec()
does