首页 > 解决方案 > 当新用户注册时,我想将通知推送到 mongo DB 的通知集合中

问题描述

我正在使用 MERN 堆栈。当新用户注册时,我想将通知推送到 Mongo DB 的通知集合中。以前我使用过firebase,使用谷歌云功能很容易将通知推送到firestore。我搜索了很多,但没有找到解决方案。

标签: node.jsreactjsmongodbpush-notificationnotifications

解决方案


您可以使用 mongoose 的 pre-save hooks,为此您需要创建 User Schema 和 Notification Schema,然后在 UserSchema pre-save 中创建一个新的通知,如下例所示。

// modals/User.js    

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const Notification = require('./Notification.js').Notification;


var UserSchema = new Schema({
    first_name: {
        type: String,
        required: true
    },

    last_name: {
        type: String,
        required: true
    },

    ......
});

UserSchema.post('save', function(doc) {
    var NewData = new Notification({
        user_id: doc._id,
        text: "Welcome to application"
    });

    NewData.save(function(err, notification_data) {
        // any error logging or other operations
    });
});

//make this available to our users in Node applications
module.exports.User = mongoose.model('User', UserSchema);

在 Notification.js 中,您可以根据需要创建架构。


推荐阅读