虚拟 getter 函数中的猫鼬过滤

时间:2021-06-29 06:13:13

标签: mongodb express mongoose mongoose-schema mongoose-populate

我正在尝试获取一个作为 no_of_unread_notifications 的虚拟字段。 所以基本上

  1. 我需要创建一个异步 getter 函数
  2. 在函数内部我需要查询和过滤掉 unread_notifications
  3. 最后返回过滤后的数组长度

这是我的方案:

const UserSchema = new Schema < UserDocument > ({
  name: {
    type: String,
    required: true,
  },
  ...
  ...

  notifications: [{
    type: Schema.Types.ObjectId,
    ref: "Notification"
  }],
}, {
  id: false,
  timestamps: true,
  toObject: {
    virtuals: true,
  },
  toJSON: {
    virtuals: true,
  },
});

const NotificationSchema = new Schema < NotificationDocument > ({
  userFrom: {
    type: Schema.Types.ObjectId,
    ref: "User"
  },
  notificationType: String,
  read: {
    type: Boolean,
    default: false
  },
  entityId: Schema.Types.ObjectId,
}, {
  timestamps: true
});
这是过滤掉 unread_notis 的代码。
const user = await User.findById(req.user._id).populate("notifications", "read");
const unreadNotifications = user.notifications.filter((notification) => !notification.read);
const noOfUnreadNotifications = unreadNotifications.length

现在我面临几个问题:

  1. 如何将这个异步代码放入 getter

// this is what I have tried which creates an infinite loop as the promise is never reolved
UserSchema.virtual("no_of_unread_notifications").get(async function(this: UserDocument) {
  const user = await User.findById(this._id).populate("notifications", "read");

  const unreadNotifications = user.notifications.filter((notification) => !notification.read);
  console.log(unreadNotifications);

  return unreadNotifications.length;
});

  1. 如何只使用猫鼬来过滤它,就像这样

const user = await User.findById(req.user._id).populate("notifications", {
  match: {
    read: false
  },
});
// problem is it returns the user object 

0 个答案:

没有答案
相关问题