在mongodb通知架构中存储不同的ID

时间:2018-10-25 05:44:53

标签: node.js mongodb mongoose notifications

我试图在我的应用程序中实现通知,但是在弄清楚如何将发送方和接收方的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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

只需在通知

中的推送用户数据时更改变量名称
let sender = new User({id: user._id, name: user.name}):
newNotification.sender.push(sender); //for store sender

let reciever = new User({id: user._id, name: user.name}):
newNotification.receiver.push(reciever); //for store reciever