Return certain fields with .populate() from Mongoose

前端 未结 10 1577
栀梦
栀梦 2021-01-30 10:11

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 a

10条回答
  •  猫巷女王i
    2021-01-30 10:27

    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;
        }
      });
    

提交回复
热议问题