Return certain fields with .populate() from Mongoose

前端 未结 10 1537
栀梦
栀梦 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条回答
  • 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;
        }
      });
    
    0 讨论(0)
  • 2021-01-30 10:27

    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
    ...
    

    See Mongoose populate field selection

    0 讨论(0)
  • 2021-01-30 10:27

    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);
    }
    
    0 讨论(0)
  • 2021-01-30 10:27

    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.

    let articles = await articleModel
            .find({ show: true }, { title: 1, createdAt: 1 })
            .populate("category", { title: 1, _id: 1 });
    
    0 讨论(0)
  • 2021-01-30 10:29

    Just to complement the answers above, if you want to include everything but only exclude certain attributes, you can do the following:

    .populate('users', {password: 0, preferences: 0})
    
    0 讨论(0)
  • 2021-01-30 10:32

    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();
    
    0 讨论(0)
提交回复
热议问题