简体   繁体   English

使用 Mongoose 的 .populate() 返回某些字段

[英]Return certain fields with .populate() from Mongoose

I'm getting returned a JSON value from MongoDB after I run my query.运行查询后,我从 MongoDB 返回了一个 JSON 值。 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.问题是我不想返回与我的返回相关的所有 JSON,我尝试搜索文档但没有找到合适的方法来执行此操作。 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.对于上面的示例,我想返回 RMS 的[email][address]字段和 Zuckerburg 的[facebook][address]字段。 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");
      }
    }
  }

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()查询,以便您可以自由修改输出,然后填充这两个字段并对结果进行后处理以仅保留该字段你要:

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

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.如果您只想为填充的文档返回几个特定的​​字段,您可以通过将字段名称语法作为第二个参数传递给 populate 方法来实现这一点。

Model
.findOne({ _id: 'bogus' })
.populate('the_field_to_populate', 'name') // only return the Persons name
...

See Mongoose populate field selection请参阅猫鼬填充字段选择

Try to do this:尝试这样做:

applicantListToExport: function (query, callback) {
  this
   .find(query).select({'advtId': 0})
   .populate({
      path: 'influId',
      model: 'influencer',
      select: { '_id': 1,'user':1},
      populate: {
        path: 'userid',
        model: 'User'
      }
   })
 .populate('campaignId',{'campaignTitle':1})
 .exec(callback);
}

尝试这样做:

User.find(options, '_id user email facebook').populate('facebook', '_id pos').exec(function (err, users) {

现在你可以做的是:

  .populate('friends', { username: 1, age: 1})

In the following query i retrieved articles which match the condition show=true the retrieved data title and createdAt also retrieve the category of article only the title of category and it's id.在下面的查询中,我检索了与条件匹配的文章show=true检索到的数据title and createdAt还检索了文章的类别,只有类别的标题和它的 id。

let articles = await articleModel
        .find({ show: true }, { title: 1, createdAt: 1 })
        .populate("category", { title: 1, _id: 1 });

you to try :你试试:

Post.find({_id: {$nin: [info._id]}, tags: {$in: info.tags}}).sort({_id:-1})
.populate('uid','nm')
.populate('tags','nm')
.limit(20).exec();

只是为了补充上面的答案,如果您想包含所有内容但只排除某些属性,您可以执行以下操作:

.populate('users', {password: 0, preferences: 0})

Hi for me it worked for me i populated user field using the populate code : --->嗨对我来说它对我有用我使用填充代码填充了用户字段:--->

async function displayMessage(req,res,next){
    try{
        let data= await Msg.find().populate("user","userName userProfileImg","User")
               if(data===null) throw "Data couldn ot be loaded server error"
        else {
            res.status(200).json(data)
        }
    }   catch(err){
            next(err)
    }
}

i am directly getting the result .我直接得到结果。 Here the fields userName , userProfile image are the ones that ive required selectively and the syntax for populate is :-->这里的字段 userName , userProfile image 是我有选择地需要的字段,填充的语法是:-->

 .populate("user field to populate","fields to display with spaces between each of them " , "modelName ")

every parameter should be in inverted comma's.每个参数都应该用引号引起来。

Below is the output i recieve.One more thing you don't have to worry about the populating sub-document id you will automatically get them.下面是我收到的输出。还有一件事,您不必担心填充的子文档 ID,您将自动获取它们。

[
    {
        "_id": "5e8bff324beaaa04701f3bb9",
        "text": "testing message route",
        "user": {
            "_id": "5e8bf062d3c310054cf9f293",
            "userName": "boss",
            "userProfileImg": "img"
        },
        "__v": 0
    },
    {
        "_id": "5e8bff8dd4368a2858e8f771",
        "text": "testing message route second",
        "user": {
            "_id": "5e8bf062d3c310054cf9f293",
            "userName": "boss",
            "userProfileImg": "img"
        },
        "__v": 0
    },
    {
        "_id": "5e8c0c08e9bdb8209829176a",
        "text": "testing message route second",
        "user": {
            "_id": "5e8bf062d3c310054cf9f293",
            "userName": "boss",
            "userProfileImg": "img"
        },
        "__v": 0
    },
    {
        "_id": "5e8c0e0bcb63b12ec875962a",
        "text": "testing message route fourth time",
        "user": {
            "_id": "5e8bf062d3c310054cf9f293",
            "userName": "boss",
            "userProfileImg": "img"
        },
        "__v": 0
    }
]

for a single level populate you can use -> populate('user','name email age')对于单级填充,您可以使用-> populate('user','name email age')

for nested population对于嵌套种群

populate({
    path:'posts',
    populate({
         path:'user'
         select:'name email age'
    })
})

I was stuck on this issue.我被困在这个问题上。 I wanted to populator and user field linked to the Blog Post.我想将填充器和用户字段链接到博客文章。 Using populate only returned everything including the password .使用填充只返回包括密码在内的所有内容。 By specifying fields as an array it works fine.通过将字段指定为数组,它可以正常工作。

//code emitted for brevity //为简洁而发出的代码

await Blog.findById(ID).populate("author", ["firstName", "lastName", 
"profilePicture", "_id"])

// //

This is the result of the response这是响应的结果

回复

you can try using below,你可以尝试使用下面,

 Model
    .find()
    .populate({path: 'foreign_field', ['_id', 'name']}) // only return the Id and Persons name
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM