我正在尝试获取一个作为 no_of_unread_notifications 的虚拟字段。 所以基本上
这是我的方案:
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
});
const user = await User.findById(req.user._id).populate("notifications", "read");
const unreadNotifications = user.notifications.filter((notification) => !notification.read);
const noOfUnreadNotifications = unreadNotifications.length
现在我面临几个问题:
// 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;
});
const user = await User.findById(req.user._id).populate("notifications", {
match: {
read: false
},
});
// problem is it returns the user object