如何使用mongoose在mongodb中有条件地填充数组中的文档

yv5phkfx  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(128)

我只想得到与req.query中请求的状态、from_date和to_date相匹配的用户的通知。
用户架构:

const userSchema = mongoose.Schema({
email: {
    type: String,
    required: true
},
password: {
    type: String,
    minlength: 8,
    required: true
},
notifications: [{
    notification: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Notification"
    },
    status: {
        type: String,
        enum: ["Not Acknowledged", "Acknowledged"],
        default: "Not Acknowledged"
    },
 }]
})

字符串
通知架构:

const notificationSchema = mongoose.Schema({
  description: {
      type: String
  },
  remind_on: {
      type: Date
  },
  remind_at: {
      type: Date
  },
});


我试过了,但它会发出所有通知。

const statusQuery = {};
  if(status) {
    statusQuery.match = { 'notifications.status': status }
  }
  const searchNotifications = await User.findById(user._id)
    .populate({
      path: "notifications",
      ...statusQuery,
      populate: {
        path: "notification",
        populate: [
          { path: "assignee", select: "first_name last_name" },
          { path: "case", select: "case_id" },
        ],
      },
    })
    .select("notifications");


在上面的代码中,我首先通过用户ID获取用户文档,并尝试在populate中添加查询

rdrgkggo

rdrgkggo1#

要根据您的问题根据状态、from_date和to_date过滤通知,您需要根据from_dateto_date指定的日期范围内的remind_onremind_at字段为通知添加过滤器。
这里有一个同样的例子。

// Sample values for `status`, `from_date`, and `to_date`
const status = "Acknowledged"; // or "Not Acknowledged"
const from_date = new Date("2023-01-01");
const to_date = new Date("2023-12-31");

// Find the user and populate notifications
const searchNotifications = await User.findById(user._id)
  .populate({
    path: "notifications.notification",
    match: {
      ...(status && { 'status': status }), // Filter by status
      remind_on: { 
        $gte: from_date, 
        $lte: to_date 
      } // Filter by date range
    },
    populate: [
      { path: "assignee", select: "first_name last_name" },
      { path: "case", select: "case_id" }
    ]
  })
  .select("notifications");

// Filtering out notifications that did not match the query
const filteredNotifications = searchNotifications.notifications.filter(n => n.notification != null);

console.log(filteredNotifications);

字符串

相关问题