Getting error in mongodb cast issue for valid object id

后端 未结 2 1804
有刺的猬
有刺的猬 2021-01-25 05:06

My code was working fine but after taking fresh code I am getting this error but as I can see my id is valid Object Id

Cast to ObjectId

相关标签:
2条回答
  • 2021-01-25 05:35

    You have to cast the data to mongodb object id. If you are using mongoose, you can actually do these below.

    const mongoose = require('mongoose');
    const ObjectId = mongoose.Types.ObjectId;
    
    [your_mongodb_model/collection].query({ _id: ObjectId(id) });
    

    or simply, you can do these,

    [your_mongodb_model].query({ _id: mongoose.Types.ObjectId(id) });
    
    0 讨论(0)
  • 2021-01-25 05:54

    The reason for this error is documented in this mongoose issue. A workaround is to downgrade to mongoose version <= 4.7.2 or use Node version >=6.

    0 讨论(0)
提交回复
热议问题