聚合函数Mongoose -节点

mdfafbf1  于 2022-11-24  发布在  Go
关注(0)|答案(1)|浏览(112)

我有一个架构

const membershipsSchema = new Schema({
  spaceId: {
    type: Schema.Types.ObjectId,
    ref: 'Space',
  },
  member: {
    type: Schema.Types.ObjectId,
    ref: 'User',
  },
  ....
);

mongoose.model('Membership', membershipsSchema);

我想使用如下连接语句

Select * from membershipPlans as plans join User as users on plans.member=users._id
where plans.spaceId=id and users.status <> 'archived'; // id is coming from function arguments

我尝试了aggregate管道,如

const memberships = await Memberships.aggregate([
  {
    $match: {
      spaceId: id
    }
  },
  {
    $lookup: {
      from: 'User',
      localField: 'member',
      foreignField: '_id',
      as: 'users',
    },
  },
  {
    $match: {
      'users.status': {$ne: 'archived'}
    }
  },
]);

但是在console.log(memberships);上我得到了一个空的数组。如果我尝试return Memberships.find({ spaceId: id }),它会返回该空间的填充成员。但是当我尝试

const memberships = await Memberships.aggregate([
  {
    $match: {
      spaceId: id
    }
  },
]}

它仍然返回空数组。不确定我是否知道如何使用aggregate管道。

osh3o9ms

osh3o9ms1#

您需要做两件事:
1.将id转换为ObjectId
1.不使用$match,而使用$filter过滤users数组的内容。
试试看:

const memberships = await Memberships.aggregate([
  {
    $match: {
      spaceId: new mongoose.Types.ObjectId(id)
    }
  },
  {
    $lookup: {
      from: 'User',
      localField: 'member',
      foreignField: '_id',
      as: 'users',
    },
  },
  {
    $project: {
      users: {$filter: {
         input: "$users",
         as: "user",
         cond: {
           $ne: ["$$user.status", "archived"]
         }
      }}
    }
  },
]);

相关问题