问题描述
我正在尝试获取一个作为 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
现在我面临几个问题:
- 如何将这个异步代码放入 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;
});
- 如何只使用猫鼬来过滤它,就像这样
const user = await User.findById(req.user._id).populate("notifications",{
match: {
read: false
},});
// problem is it returns the user object
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)