How to check if a field is populated from mongoose after using lean()

Viewed 132

Mongoose has a feature to check if a field is populated. But this only works as long as the response object is a mongoose object. Once I use lean() on my query, I'm not able to check if the field is populated.

Question:

  1. I have a field, that has to be checked if it's populated. I'm running a lean() query and now I'm unable to figure out if the field is populated.
  2. When I check the typeof for the field, it shows it's an object.
  3. Is there any way to check if a field is populated if it is a lean() query?
1 Answers

Bases on https://mongoosejs.com/docs/populate.html#checking-populated I have created a somewhat doubtful solution for this problem.

lean() makes it a POJO (Plain Old Json Object). Therefore, no mongoose functions are present anymore because that it the whole point of using lean(): Lightweight objects. More on lean: https://mongoosejs.com/docs/tutorials/lean.html#using-lean

When still in query, you can use populate on your query after lean: https://mongoosejs.com/docs/tutorials/lean.html#lean-and-populate

const group = await Group.findOne().lean().populate('members');
group.members[0].name; // 'Benjamin Sisko'
group.members[1].name; // 'Kira Nerys'

If you do not know anything about your object, you can use the original model to populate it:

group = await Group.populate(group, 'members')

Check https://mongoosejs.com/docs/populate.html#populate_multiple_documents for more info

Related