Home > front end >  Mongoose result always empty when tring to filter
Mongoose result always empty when tring to filter

Time:04-27

I'am trying to fetch by the field doctorId which is of type objectId, however it always returns an empty array. I tested it without the filter and it works fine so I don't think it's an error envolving the model or connection: Mocha test:

mongoose.connect('mongodb://localhost:27017/test')

chai.should()

describe('Get treatments by doctorId', () => {
    it("get two entries", async () => {
        const treatments = await repository.getByDoctorId(new mongoose.Types.ObjectId("6260a98cbad424eec4818556"))
        console.log(treatments)
        treatments.should.not.be.empty
    })
})

And the function I'am using to fetch the data:

const getByDoctorId = async (doctorId) =>{
    console.log(doctorId)
    try{
        return await Treatment.find({doctorId: doctorId})
    }catch(ex){
        return null
    }
}

The data I'm tring to fetch: enter image description here

CodePudding user response:

Based on the image you showed, doctorId is not an ObjectId. It's a string. See the difference between it and _id (that's an ObjectId).

It apparently has the same format as an ObjectId, but filtering as if it were one is expected to give no results. MongoDB's ObjectId is not the same as a string, even if they look the same.

To have the behavior you want, simply change your repository call to something like:

        const treatments = await repository.getByDoctorId("6260a98cbad424eec4818556")

That should do the trick.


Note: avoid showing information like that in images. It usually scares help away.

  • Related