Yash Gupta
Yash Gupta

Reputation: 165

How to Add Notifications in mongoose?

I have this user schema

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;

I want to send notification to everyone when a user creates a blog or add a comment how can I implement this? should I use triggers?

The strategy behind this

Upvotes: 0

Views: 985

Answers (1)

Ashish Modi
Ashish Modi

Reputation: 7770

I guess this can be easily achieved by using mongodb change streams.

You can see more about here with code examples.

power of mongodb change streams

Basically listen for insert/update operation type and react accordingly.

Upvotes: 1

Related Questions