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

{
    user: "RMS",
    OS: "GNU/HURD",
    bearded: "yes",
    philosophy: {
        software: "FOSS",
        cryptology: "Necessary"
    },
    email: {
        responds: "Yes",
        address: "rms@gnu.org"
    },
    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");
      }
    }
  }

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:

.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;
    }
  });
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement