猫鼬“反向"填充,即基于子模式中定义的引用填充父对象 [英] Mongoose 'reversed' population, i.e. populating a parent object based on the reference defined in child schema

查看:81
本文介绍了猫鼬“反向"填充,即基于子模式中定义的引用填充父对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们从

Let's borrow the excellent example from scaryguy with modification as below:

项目组架构:

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

然后我可以进行以下填充:

Then I can do following population:

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

请注意,参考字段不是对象ID.

Note that the reference fields are not Object IDs.

在此示例中,项目模式具有对项目组和订户的引用字段,这使得上述填充成为可能.

In this example the project schema has the reference fields to both the project group and subscribers which makes the above population possible.

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

What if I want to get a ProjectGroup object, which contains all the projects under that group, and each project contains its subscribers?

我要说的是寻找反向"人群,即根据子模式中定义的引用填充父对象. 目前,我先使用async来查询ProjectGroup,然后再根据projectGroupId查询项目.

I'd say I'm looking for a 'reversed' population, i.e. populating a parent object based on the reference defined in child schema. At the moment I use async to query the ProjectGroup first, then query the projects based on the projectGroupId.

谢谢!

推荐答案

您可以通过使用聚合函数来实现.首先通过"projectGroup"对项目进行分组,然后填充结果.

You can achieve this by using aggregate function. First group projects by "projectGroup" and then populate result.

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

});

这篇关于猫鼬“反向"填充,即基于子模式中定义的引用填充父对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆