猫鼬有条件地填充子文档

the*_*i11 6 mongoose mongodb node.js

我有一个如下所示的架构:

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
});
Run Code Online (Sandbox Code Playgroud)

组和用户将导出为其自己的集合。我有一个端点 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);
      });

    });
Run Code Online (Sandbox Code Playgroud)

但是,如果组类型==“特殊”,我不想填充每个成员的关联用户。我该如何添加选项来做到这一点?

小智 4

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

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

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);
});
Run Code Online (Sandbox Code Playgroud)

因此,在 groups 数组内,您有一些已填充的文档,而有些则未填充。这很奇怪,但你可以使用specialGroups而不是user.groups