对多个填充字段的猫鼬查询

Mongoose query on multiple populated fields

我有三个合集,即 EventsNewsFuneralNews。 我有另一个 Notifications 集合,它只是所有三个集合的组合,并且包含三个集合的 either/one 的引用 ID。

我只想获取那些 Notifcations 的 eventId OR newsId OR funeralNewsId 字段 isActive 为 true

事件架构:

var EventsSchema = new Schema({
  ...
  isActive: Boolean
});

FuneralNewsSchema:

var FuneralNewsSchema = new Schema({
  ...
  isActive: Boolean
});

新闻架构:

var NewsSchema = new Schema({
  ...
  isActive: Boolean
});

通知架构:

var NotificationSchema = new Schema({
  type: {
    type: String,
    required: true
  },
  creationDate: {
    type: Date,
    default: Date.now
  },
  eventId: {type: Schema.Types.ObjectId, ref: 'Events'},
  newsId: {type: Schema.Types.ObjectId, ref: 'News'},
  funeralNewsId: {type: Schema.Types.ObjectId, ref: 'FuneralNews'},
  organisationId: {type: Schema.Types.ObjectId, ref: 'Organization'}
});

这是我在需要检查引用集合的 isActive 属性 之前的查询:

  let totalItems;
  const query = { organisationId: organisationId };

  Notification.find(query)
    .countDocuments()
    .then((count) => {
      totalItems = count;
      return Notification.find(query, null, { lean: true })
        .skip(page * limit)
        .limit(limit)
        .sort({ creationDate: -1 })
        .populate("eventId")
        .populate("newsId")
        .populate("funeralNewsId")
        .exec();
    })
    .then((notifications, err) => {
      if (err) throw new Error(err);
      res.status(200).json({ notifications, totalItems });
    })
    .catch((err) => {
      next(err);
    });

现在我不知道如何检查 isActive 填充前三个填充集合的字段。

我已经看到其他问题,例如 and this 但是作为新手无法根据我的用例对其进行编辑。任何帮助将不胜感激

对每个 objectId 引用使用 $lookup 然后 group 通过 null 的 _id 获取数据并将 myCount 作为总数将原始数据添加到数组 并使用 unwind 破坏数组并使用 addField

model
  .aggregate([
    {
      $lookup: {
        from: "Events", // events collection name
        localField: "eventId",
        foreignField: "_id",
        as: "events",
      },
    },
    {
      $lookup: {
        from: "FuneralNews", //FuneralNews collection name
        localField: "funeralNewsId",
        foreignField: "_id",
        as: "funeralnews",
      },
    },
    {
      $lookup: {
        from: "News", // news collection name
        localField: "newsId",
        foreignField: "_id",
        as: "news",
      },
    },
    {
      $match: {
        $or: [
          { "news.isActive": true },
          { "events.isActive": true },
          { "funeralnews.isActive": true },
        ],
      },
    },

    {
      $group: {
        _id: null,
        myCount: {
          $sum: 1,
        },
        root: {
          $push: "$$ROOT",
        },
      },
    },
    {
      $unwind: {
        path: "$root",
      },
    },
    {
      $addFields: {
        "root.total": "$myCount",
      },
    },
    {
      $replaceRoot: {
        newRoot: "$root",
      },
    },

    {
      $sort: {
        creationDate: -1,
      },
    },
  ])
  .skip(page * limit)
  .limit(limit);