Я пытаюсь внедрить уведомления в свое приложение, но мне сложно понять, как сохранить идентификаторы отправителя и получателя в моей схеме уведомлений ниже.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const notificationSchema = mongoose.Schema({
sender: [{
type: Schema.Types.ObjectId,
ref: 'user'
}],
receiver: [{
type: Schema.Types.ObjectId,
ref: 'user'
}],
seen: {
type: Boolean
},
notificationMessage: {
type: String
},
created: {
type: Date
}
})
const Notifications = mongoose.model('notification', notificationSchema);
module.exports = Notifications;
У меня есть контроллерпри попытке создать новое уведомление ниже
const User = require('../models/User');
const Notification = require('../models/Notification');
module.exports = {
getNotifications: async (req, res, next) => {
const { _id } = req.params;
const user = await User.findById(_id).populate('notification');
console.log('user', user)
res.status(200).json(user.notifications);
},
createNotification: async (req, res, next) => {
const { _id } = req.params;
const newNotification = new Notification(req.body);
console.log('newNotification', newNotification);
const user = await User.findById(_id);
newNotification.user = user;
await newNotification.save();
let sender = new User({id: user._id});
newNotification.sender.push(sender);
let receiver = new User({id: user._id});
newNotification.receiver.push(receiver);
await user.save();
res.status(201).json(newNotification);
}
}
Проблема в том, что когда я пытаюсь создать уведомление, ничего не сохраняется, схема уведомлений возвращается с этим.
newNotification { sender: [], receiver: [], _id: 5bd1465d08e3ed282458553b }
Яне совсем уверен, как я могу сохранить идентификаторы пользователей в соответствующих ссылках в схеме уведомлений, есть ли какие-либо идеи о том, что я могу сделать, чтобы это исправить?
РЕДАКТИРОВАТЬ: изменено createNotification