#mongodb #express #mongoose #mongoose-schema #mongoose-populate
Вопрос:
Я пытаюсь получить виртуальное поле как 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