Home > Net >  Why the query manipulation is not working?
Why the query manipulation is not working?

Time:09-27

I made a handler factory function to handle some API. There I have a populate method to populate a field in database. After execution I saw my populate method is not working when I use query manipulation like . . .

        let query = await Model.findById(req.params.id)
        
        if(popOptions) query = query.populate(popOptions)
            
        

         const doc = await query

after going to the api by this controller I get the query without population

But when I use this code below using if else statement it gives me the expected output that is the query I made with population of required fields

     let query
        if(popOptions) {
            query = await Model.findById(req.params.id).populate(popOptions)
        }
        else {
            query = await Model.findById(req.params.id)
        }

    
   

I just want to know why this happens. I'm fairly new to mongoDB and express

CodePudding user response:

There is a difference between

await Model.findById(req.params.id).populate(popOptions)

and

await (await Model.findById(req.params.id)).populate(popOptions)

Try this:

let query = Model.findById(req.params.id)
        
if(popOptions) query = query.populate(popOptions)

const doc = await query
  • Related