首页 > 解决方案 > 在 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

标签: node.jsmongodbmongoosenotifications

解决方案


您正在尝试存储ObjectId在数组中,但添加整个user对象和猫鼬模式不允许未在模式中定义的字段,因此newNotification.sender.push(user._id)createNotification函数中进行更改。


推荐阅读