【问题标题】:How to Add Notifications in mongoose?如何在猫鼬中添加通知?
【发布时间】:2020-02-27 22:14:45
【问题描述】:

我有这个用户架构

const Schema = mongoose.Schema;
const bcrypt = require("bcryptjs");

const userSchema = new Schema(
  {
    email: {
      type: String,
      required: true,
      index: {
        unique: true
      }
    },
    password: {
      type: String,
      required: true
    },
    name: {
      type: String,
      required: true
    },
    website: {
      type: String
    },
    bio: {
      type: String
    }
  },
  {
    timestamps: {
      createdAt: "created_at",
      updatedAt: "updated_at"
    },
    toJSON: { virtuals: true }
  }
);

userSchema.virtual("blogs", {
  ref: "Blog",
  localField: "_id",
  foreignField: "author"
});

userSchema.pre("save", function(next) {
  const user = this;
  if (!user.isModified("password")) return next();

  bcrypt.genSalt(10, function(err, salt) {
    if (err) return next(err);

    bcrypt.hash(user.password, salt, function(err, hash) {
      if (err) return next(err);

      user.password = hash;
      next();
    });
  });
});

userSchema.methods.comparePassword = function(password, next) {
  bcrypt.compare(password, this.password, function(err, isMatch) {
    if (err) return next(err);
    next(null, isMatch);
  });
};

const User = mongoose.model("User", userSchema);
module.exports = User;

我想在用户创建博客或添加评论时向所有人发送通知,我该如何实现?我应该使用触发器吗?

这背后的策略

  • 您有多个用户。
  • 您有多个通知,可能针对单个用户、某些用户或所有用户。
  • 您需要存储中的通知“已读”条目,以了解用户是否已阅读通知。

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    我想这可以通过使用 mongodb 更改流轻松实现。

    您可以通过代码示例在此处查看更多信息。

    power of mongodb change streams

    基本上监听插入/更新操作类型并做出相应反应。

    【讨论】:

      猜你喜欢
      • 2020-05-15
      • 2019-11-20
      • 2017-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-10
      • 2019-01-20
      • 1970-01-01
      相关资源
      最近更新 更多