Skip to content
Advertisement

Return certain fields with .populate() from Mongoose

I’m getting returned a JSON value from MongoDB after I run my query. The problem is I do not want to return all the JSON associated with my return, I tried searching the docs and didn’t find a proper way to do this. I was wondering what if it is at possible, and if so what is the proper way of doing such. Example: In the DB

JavaScript

What would be the proper way of returning a field if it exists for a user, but if it doesn’t return another field. For the example above I would want to return the [email][address] field for RMS and the [facebook][address] field for Zuckerburg. This is what I have tried to find if a field is null, but it doesn’t appear to be working.

JavaScript

Advertisement

Answer

I’m not completely clear on what you mean by “returning a field”, but you can use a lean() query so that you can freely modify the output, then populate both fields and post-process the result to only keep the field you want:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement