Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

{     user: "RMS",     OS: "GNU/HURD",     bearded: "yes",     philosophy: {         software: "FOSS",         cryptology: "Necessary"     },     email: {         responds: "Yes",         address: "[email protected]"     },     facebook: {} }  {     user: "zuckerburg",     os: "OSX",     bearded: "no",     philosophy: {         software: "OSS",         cryptology: "Optional"     },     email: {},     facebook: {         responds: "Sometimes",         address: "https://www.facebook.com/zuck?fref=ts"     } }  

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.

 .populate('user' , `email.address`)   .exec(function (err, subscription){      var key;     var f;     for(key in subscription){       if(subscription[key].facebook != null  ){           console.log("user has fb");       }     }   } 
like image 668
Sleep Deprived Bulbasaur Avatar asked Nov 01 '14 18:11

Sleep Deprived Bulbasaur


People also ask

How do I populate specific data in MongoDB?

If you only want a few specific fields to be returned for the populated documents, you can accomplish this by passing the field name syntax as the second argument to the populate method. Model . findOne({ _id: 'bogus' }) . populate('the_field_to_populate', 'name') // only return the Persons name ...

What does populate method do mongoose?

Mongoose Populate() Method. In MongoDB, Population is the process of replacing the specified path in the document of one collection with the actual document from the other collection.

Does Mongoose populate use lookup?

Mongoose's populate() method does not use MongoDB's $lookup behind the scenes. It simply makes another query to the database. Mongoose does not have functionalities that MongoDB does not have.


1 Answers

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:

.lean().populate('user', 'email.address facebook.address')   .exec(function (err, subscription){      if (subscription.user.email.address) {         delete subscription.user.facebook;     } else {         delete subscription.user.email;     }   }); 
like image 66
JohnnyHK Avatar answered Oct 02 '22 21:10

JohnnyHK