I created a handler factory function for managing an API, which includes a populate method to fill in a field in the database. However, I encountered an issue where my populate method was not working when using query manipulation.
let query = await Model.findById(req.params.id)
if(popOptions) query = query.populate(popOptions)
const doc = await query
When accessing the API through this controller, the query returned without the populated fields.
However, by implementing the code below with an if else statement, I was able to achieve the desired outcome of having the query populated with the necessary fields:
let query
if(popOptions) {
query = await Model.findById(req.params.id).populate(popOptions)
}
else {
query = await Model.findById(req.params.id)
}
I am curious as to why this discrepancy occurs. As someone who is relatively new to MongoDB and Express, any insights would be greatly appreciated.