Javascript 是否可以筛选并仅带回每个notificationType/postId中的一个?

Javascript 是否可以筛选并仅带回每个notificationType/postId中的一个?,javascript,node.js,mongodb,express,mongoose,Javascript,Node.js,Mongodb,Express,Mongoose,我有一个通知模型和这个模式在这里: const NotificationSchema = new Schema({ type: { type: String, required: true }, createdAt: { type: Number, required: true }, postId: { type: Schema.Types.ObjectId, ref: 'post', required: true

我有一个
通知
模型
和这个
模式
在这里:

const NotificationSchema = new Schema({
  type: {
    type: String,
    required: true
  },
  createdAt: {
    type: Number,
    required: true
  },
  postId: {
    type: Schema.Types.ObjectId,
    ref: 'post',
    required: true
  },
  recipients: [{
    type: Schema.Types.ObjectId,
    ref: 'user',
    required: true
  }]
});
getNotifications(req, res, next) {
    const userId = req.params.id;

    Notification.find({ recipients: userId })
      .sort({ createdAt: 1 })
      .then(notifications => res.send(notifications))
      .catch(next);
  },
我正在构建一个路线控制器,该控制器将获取所有
通知
,其中他们是
收件人之一,如下所示:

const NotificationSchema = new Schema({
  type: {
    type: String,
    required: true
  },
  createdAt: {
    type: Number,
    required: true
  },
  postId: {
    type: Schema.Types.ObjectId,
    ref: 'post',
    required: true
  },
  recipients: [{
    type: Schema.Types.ObjectId,
    ref: 'user',
    required: true
  }]
});
getNotifications(req, res, next) {
    const userId = req.params.id;

    Notification.find({ recipients: userId })
      .sort({ createdAt: 1 })
      .then(notifications => res.send(notifications))
      .catch(next);
  },
我还想确保,如果有多个
通知
具有相同的
类型
,例如
postAuthorNotification
和相同的
postId
,那么它只会返回具有最新
createdAt
时间戳的
通知

原因是如果一个用户的帖子被评论了20次。每一个都会有一个
通知
。不过,我只想向用户发回一个最新的通知

对于猫鼬/猫鼬,这可能吗


谢谢。

您已经链接了
.sort()
方法,该方法将按
createdAt
对结果进行排序。要将结果限制为仅1个,只需将
.limit(1)
链接到查询即可

限值的官方文件
方法-