Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

Implementing cascades in mongoose

const mongoose = require("mongoose");
const User = require("./user");

const RoleSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true
  }
});

RoleSchema.post("remove", document => {
  const roleId = document._id;
  User.find({ roles: { $in: [roleId] } }).then(users => {
    Promise.all(
      users.map(user =>
        User.findOneAndUpdate(
          user._id,
          { $pull: { roles: roleId } },
          { new: true }
        )
      )
    );
  });
});

module.exports = mongoose.model("Role", RoleSchema);
Source by dev.to #
 
PREVIOUS NEXT
Tagged: #Implementing #cascades #mongoose
ADD COMMENT
Topic
Name
4+5 =