【发布时间】:2018-10-25 20:52:27
【问题描述】:
我正在尝试在我的应用中实现通知,但我无法弄清楚如何将发送者和接收者的 ID 存储到下面的通知架构中。
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 }
我不完全确定如何将用户 ID 存储到通知架构中各自的引用中,知道我可以做些什么来解决这个问题吗?
编辑:更改了 createNotification
【问题讨论】:
标签: node.js mongodb mongoose notifications