Search code examples
javascriptmongodbexpressmongoose-schema

Why the query manipulation is not working?


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


Solution

  • 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