【问题标题】:Storing different id's in mongodb notification schema在 mongodb 通知模式中存储不同的 id
【发布时间】: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


    【解决方案1】:

    通知推送用户数据时只需更改变量名称即可

    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
    

    【讨论】:

    • 刚刚尝试过,但发送方和接收方字段仍然为空。还有什么我可以尝试帮助的吗?谢谢
    • @Sharkows Abel 请尝试我更新的答案可能对您有所帮助
    • 所以现在,通知模式正在保存发送者和接收者的 ID,但在用户模式中,通知字段仍然是空的,我得到类型:错误无法读取 null 的属性“id”。知道会发生什么吗?谢谢你陪我这么久
    • 能否请您提供您有哪些更改?
    • 修改后的帖子
    【解决方案2】:

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

    【讨论】:

    • 你能详细说明一下吗?我已将 user.notification.push(newNotification) 更改为您的建议,但现在我得到了 (node:10092) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'push' of undefined
    • 因为之前我错过了在推送之前添加sender。尝试为发送者和接收者更新 ans。
    猜你喜欢
    • 2020-10-17
    • 2020-06-15
    • 2022-01-02
    • 1970-01-01
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    • 2014-06-09
    • 2015-07-18
    相关资源
    最近更新 更多