node.js - 当新用户注册时,我想将通知推送到 mongo DB 的通知集合中
问题描述
我正在使用 MERN 堆栈。当新用户注册时,我想将通知推送到 Mongo DB 的通知集合中。以前我使用过firebase,使用谷歌云功能很容易将通知推送到firestore。我搜索了很多,但没有找到解决方案。
解决方案
您可以使用 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 中,您可以根据需要创建架构。
推荐阅读
- java - MapStruct 子实体
- javascript - 无法 POST 到 Express 路由器(404 错误)
- r - 用 ggplot2 绘制 Shapefile
- javascript - 通过断点而不是多个 else if 语句查找索引
- php - iOS 静默远程推送通知不起作用:没有用户可见的内容
- javascript - 按下 HTML 按钮 - 使用 Javascript 检查状态(单击时不触发)
- javascript - 我似乎无法从扩展程序运行我的功能
- node.js - Fluent-FFmpeg 错误:ffprobe 以代码 1 退出
- review - 尝试使用rest api访问评论板差异时获取html页面
- mysql - 具有现有值的自动递增范围键的mysql约束