【问题标题】:Mongoose query on multiple populated fieldsMongoose 查询多个填充字段
【发布时间】:2021-11-03 06:08:30
【问题描述】:

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

我只想获取 Notifcations 的 eventId 或 newsId 或葬礼新闻 ID 字段 isActive 为 true 的那些

EventsSchema

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

FuneralNewsSchema

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

NewsSchema:

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

NotificationSchema:

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 字段。

我见过其他问题,例如 thisthis,但作为新手无法根据我的用例对其进行编辑。任何帮助将不胜感激

【问题讨论】:

    标签: mongodb mongoose mongodb-query aggregation-framework mongoose-populate


    【解决方案1】:

    对每个 objectId 引用使用 $lookup 然后group by _id of null 获取数据并添加 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);
    

    【讨论】:

    • 谢谢娜伊米。 countDocuments 呢?在哪里调整它。
    • 你可以在聚合管道中使用另一个阶段作为{$count:"countfieldname"}
    • 谢谢,但查询未填充引用的文档。我也想要人口
    • count 之后您需要人口数据吗?
    • 是的,我也想要 isActive 检查后的活动、新闻、葬礼详情
    猜你喜欢
    • 2013-07-06
    • 1970-01-01
    • 2012-07-15
    • 2012-01-22
    • 2017-05-21
    • 2015-06-09
    • 1970-01-01
    • 2021-03-03
    • 1970-01-01
    相关资源
    最近更新 更多