想要查询以聚合,查找和项目的方式获取猫鼬中的数据

时间:2018-12-27 12:37:14

标签: mongoose

用户架构如下:

def parse_1(self, response):
    item = GetIt()
    item['ID'] = response.xpath('regex').re_first('regex=(\d+)')
    url_to_get_name = ...

    yield Request(url_to_get_name, self.parse_2, meta={'item': item})

def parse_2(self, response):
    item = response.meta['item']
    item['name'] = response.xpath('regex').extract()

    yield item



用户的ChildSchema:

const UserSchema = new Schema({
  username: {
    type: String,
    required: true
  },
  communities: [ UserCommunitiesSchema ],
  createdAt: {
    type: Date,
    default: Date.now
  }
});




CommunitySchema如下:

const UserCommunitiesSchema = new Schema({
  community: { type: schema.Types.ObjectId, ref: 'CommunitySchema' },
  role: { type: String, enum: ['admin','member'], default: 'member' }
}, { _id: false });

实际结果:

const CommunitySchema = new Schema({
  admin: {
    type: schema.Types.ObjectId,
    ref: 'UserSchema'
  },
  title: {
    type: String,
    required: true,
    min: 5,
    max: 200
  },
  members: [{ 
    member: { type: schema.Types.ObjectId, ref:'UserSchema' },
    joinedAt: { type: Date, default: Date.now() }
  }],
  createdAt: { type: Date, default: Date.now() },
});

我希望返回以下数据的用户详细信息
我想在{ "_id": "ObjectId(User)", "username": "username", "communities": [ { "role": "admin", "community": "ObjectId(Comm1)" }, { "role": "member", "community": "ObjectId(Comm2)" } ], } 键的哪个位置获取每个社区的详细信息,并将其存储在communities键下。
另外,我希望每个社区的community保持原样。
我尝试了以下代码,但它代替了社区:

我尝试过的代码:

role

预期结果:

UserSchema
 .aggregate([
  { $match: { _id: new mongoose.Types.ObjectId(req.params.id) } },
  { $lookup: {
    from: 'CommunitySchema',
    let: { communities: "$communities" },
    pipeline: [
      {
        $match: {
          $expr: {
            $in: ['$_id', '$$communities.community']
          }
        }
      },
      { $project: {
        _id: 1,
        title: 1,
        membersCount: { $size: '$members' },
      }}
    ],
    as: 'communities'
  }},
 ]).then(user => console.log(user))
 .catch(error => console.log(error));

0 个答案:

没有答案
相关问题