Хранение разных идентификаторов в схеме уведомлений mongodb - PullRequest
0 голосов
/ 25 октября 2018

Я пытаюсь внедрить уведомления в свое приложение, но мне сложно понять, как сохранить идентификаторы отправителя и получателя в моей схеме уведомлений ниже.

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 }

Яне совсем уверен, как я могу сохранить идентификаторы пользователей в соответствующих ссылках в схеме уведомлений, есть ли какие-либо идеи о том, что я могу сделать, чтобы это исправить?

РЕДАКТИРОВАТЬ: изменено createNotification

Ответы [ 2 ]

0 голосов
/ 25 октября 2018

Просто измените имя переменной , когда нажмите пользователя данные в уведомление

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
0 голосов
/ 25 октября 2018

Вы пытаетесь сохранить ObjectId в массиве, но при добавлении всего объекта user и схемы mongoose не допускаются поля, которые не определены в схеме, поэтому измените newNotification.sender.push(user._id) в функции createNotification.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...