Mongoose'反向'填充,即基于子模式中定义的引用填充父对象

问题描述 投票:3回答:2

让我们从example借用优秀的scaryguy,修改如下:

项目组架构:

var ProjectGroupSchema = new Schema({
    projectGroupId    : String,
    title             : String
});

项目架构:

var ProjectSchema = new Schema({
    title         : {type : String, default : '', required : true},
    group         : {type: String, ref: 'ProjectGroup' },
    subscribers   : [{type: String, ref: 'User' }]
});

用户架构:

var UserSchema = new Schema({
    userId       : {type: String, require: true},
    firstName    : {type: String, required: true},
    lastName     : {type: String, required: true},
});

然后我可以做以下人口:

project.findById(req.projectId})
 .populate('subscribers')
 .populate('group')
 .exec(function(err, project){
      console.log(project);
 });

请注意,引用字段不是对象ID。

在此示例中,项目模式具有项目组和订户的参考字段,这使得上述人口成为可能。

如果我想获得一个ProjectGroup对象,该对象包含该组下的所有项目,并且每个项目都包含其订阅者,该怎么办?

我会说我正在寻找一个“逆转”的群体,即根据子模式中定义的引用填充父对象。目前我首先使用异步查询ProjectGroup,然后根据projectGroupId查询项目。

谢谢!

node.js mongoose mongoose-populate
2个回答
2
投票

您可以使用聚合函数来实现此目的。第一组按“projectGroup”进行项目,然后填充结果。

project.aggregate([
   {$group: {_id: "$group", projects: {$push: "$$ROOT"}}}
],
  function(err,results) {
    user.populate( results, { "path": "projects.subscribers" }, function(err,results) {
        if (err)
         console.log(err);
        res.send(results);
    });

});

3
投票

如果要获取ProjectGroup对象,该对象包含该组下的所有项目。你可以使用Populate Virtuals。 (猫鼬版> 4.5.0)

在架构文件中创建虚拟架构。

ProjectGroupSchema.virtual('projects', {
  ref: 'Project', // The model to use
  localField: 'projectGroupId', // Your local field, like a `FOREIGN KEY` in RDS
  foreignField: 'group', // Your foreign field which `localField` linked to. Like `REFERENCES` in RDS
  // If `justOne` is true, 'members' will be a single doc as opposed to
  // an array. `justOne` is false by default.
  justOne: false
});

和查询如下:

ProjectGroup.find().populate('projects').exec(function(error, results) {
  /* `results.projects` is now an array of instances of `Project` */
});

如果您看不到虚拟端口,请将{ toJSON: { virtuals: true } }设置为您的型号。

var ProjectGroupSchema = new Schema({
    projectGroupId    : String,
    title             : String
}, { toJSON: { virtuals: true } });
© www.soinside.com 2019 - 2024. All rights reserved.