【问题标题】:mongoose conditional populate on subdocument猫鼬有条件地填充子文档
【发布时间】:2015-11-27 00:57:27
【问题描述】:

我的架构如下所示:

var UserSchema = new Schema({
  name              : { type: String, required: true },
  email             : { type: String, lowercase: true },
  fences            : [{type: Schema.Types.ObjectId, ref: 'Group'}]
});

var GroupMemberSchema = new Schema({ 
    user  : { type: Schema.Types.ObjectId, ref: 'User', required: true },
  status  : { type: String, default : 'Invited' }
});

var GroupSchema = new Schema({
  name          : String,
  members       : [GroupMemberSchema],
  type          : String
});

Group 和 User 被导出为它们自己的集合。我有一个端点 api/users/me 我想在其中获取我的用户和我的所有组。在组内,我想在我的成员中填充用户。我可以使用此代码正常工作:

User.findOne({
      _id: userId
    })
    .populate('groups')
    .exec(function(err, user) { 
      if (err) return next(err);
      if (!user) return res.json(401);

      var options = {
        path: 'groups.members.user',
        model: 'User'
      };

      User.populate(user, options, function (err, user) {
        return res.json(user);
      });

    });

但是,如果组类型 == 'Special',我不想填充每个成员的关联用户。我将如何设置选项?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您可以在填充中使用“匹配”属性。

    类似这样的:

    User.findOne({
          _id: userId
        })
        .populate('groups')
        .exec(function(err, user) { 
          if (err) return next(err);
          if (!user) return res.json(401);
    
          var options = {
            path: 'groups.members.user',
            model: 'User',
            match: { 'group.type': { $ne: 'Special' } }
          };
    
          User.populate(user, options, function (err, user) {
            return res.json(user);
          });
    
        });
    

    【讨论】:

      【解决方案2】:

      您正在填充子文档,但填充机制没有区别

      只需选择类型为 !== 'Special' 的所有组并在过滤后的数组上运行填充

      var options = {
        path: 'members.user',
        model: 'User'
      };
      var specialGroups = _.filter(user.groups, function(group){return group.type !== 'Special'})
      
      User.populate(specialGroups, options, function (err, user) {
        return res.json(user);
      });
      

      因此,在 groups 数组中,您填充了一些文档而未填充了一些文档。很奇怪,但是你可以使用 specialGroups 来代替 user.groups

      【讨论】:

        猜你喜欢
        • 2021-10-07
        • 2017-05-07
        • 2021-02-11
        • 2021-10-07
        • 2016-08-17
        • 2015-07-28
        • 2021-08-29
        • 2021-04-26
        • 2013-10-05
        相关资源
        最近更新 更多