node.js - 在 mongodb 通知模式中存储不同的 id
问题描述
我正在尝试在我的应用程序中实现通知,但我无法弄清楚如何将发送者和接收者的 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
解决方案
您正在尝试存储ObjectId
在数组中,但添加整个user
对象和猫鼬模式不允许未在模式中定义的字段,因此newNotification.sender.push(user._id)
在createNotification
函数中进行更改。
推荐阅读
- android - 没有在 Logcat 中获取 facebook keyhash
- java - 每次测试后测试restful服务和清理数据库
- static - 如何读取 SAS 提示的静态列表的用户选择值
- java - Spring Bean 配置总是返回 null
- arrays - 使用角度 5 转换动态值
- swift - 动画多个原型表视图单元格
- python - 报告实验室的画布对象的正确构造方法是什么?
- ruby-on-rails - 在 Windows 上运行的 Ubuntu bash 上设置 PostgreSQL
- javascript - 赛普拉斯调用不执行隐藏元素交互的“显示”方法
- csv - 使用 p:dataexporter 导出 csv