从Mongoose返回.populate()的某些字段 [英] Return certain fields with .populate() from Mongoose

查看:660
本文介绍了从Mongoose返回.populate()的某些字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行查询后,我从MongoDB返回了一个JSON值。问题是我不想返回与我的返回相关联的所有JSON,我尝试搜索文档并且没有找到正确的方法来执行此操作。我想知道如果可能的话,如果是的话,这样做的正确方法是什么。示例:
在数据库中

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"
    }
} 

如果某个字段存在于某个用户,但如果该字段没有返回另一个字段,那么返回该字段的正确方法是什么。对于上面的例子,我想返回RMS的 [email] [地址] 字段和 [facebook] [地址] 扎克伯格的领域。这是我试图找到一个字段为空,但它似乎没有工作。

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


推荐答案

我不清楚你的意思是什么字段,但您可以使用 lean()查询,以便您可以自由修改输出,然后填充两个字段并对结果进行后处理以仅保留字段想要:

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

这篇关于从Mongoose返回.populate()的某些字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆