Delete the associated blog posts with user before deleting the respective user in mongodb and nodejs

844 Views Asked by At

When I am deleting a user, I also want to delete all the associated blog posts with that user. I have used MongoDB's pre() middleware. when it is fired it only sets the postedBy property to null in the post and then MongoDB compass the postedBy is still there along with userId here is User schema.

const crypto = require("crypto");
const mongoose = require("mongoose");
const Post = require("./post");

const userSchema = mongoose.Schema(
  {
    username: {
      type: String,
      trim: true,
      required: true,
      unique: true,
      index: true,
      lowercase: true,
    },
    name: {
      type: String,
      index: true,
      required: true,
      max: 32,
    },
    email: {
      type: String,
      index: true,
      required: true,
      trim: true,
      unique: true,
    },
    hashed_password: {
      type: String,
      required: true,
    },
    role: {
      type: Number,
      default: 0,
    },
    profile: {
      type: String,
      required: true,
    },
    photo: {
      data: Buffer,
      contentType: String,
    },
    salt: String,
    resetPassword: {
      data: String,
      default: "",
    },
  },
  { timestamp: true }
);

userSchema
  .virtual("password")
  .set(function (password) {
    this._password = password;
    this.salt = this.makeSalt();
    this.hashed_password = this.encryptPassword(password);
  })
  .get(function () {
    return this._password;
  });
userSchema.methods = {
  authenticate: function (plainText) {
    return this.encryptPassword(plainText) === this.hashed_password;
  },
  encryptPassword: function (password) {
    if (!password) return "";
    try {
      return crypto
        .createHmac("sha1", this.salt)
        .update(password)
        .digest("hex");
    } catch (err) {
      return "";
    }
  },
  makeSalt: function () {
    return Math.round(new Date().valueOf() * Math.random()) + "";
  },
};
userSchema.pre("findByIdAndRemove", function (next) {
  Post.deleteMany({ postedBy: this._id }, function (err, result) {
    if (err) {
      console.log("error");
    } else {
      console.log(result);
    }
  });
  next();
});
module.exports = mongoose.model("User", userSchema);

here is Post schema

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

const postSchema = new Schema({
  postedBy: {
    type: Schema.Types.ObjectId,
    ref: "User",
  },
  title: {
    type: String,
  },
  body: {
    type: String,
  },
  name: {
    type: String,
  },
  photo: {
    data: Buffer,
    contentType: String,
  },
  updated: Date,
  avatar: {
    type: String,
  },
  created: {
    type: Date,
    default: Date.now,
  },
  comments: [
    {
      postedBy: {
        type: Schema.Types.ObjectId,
        refPath: "onModel",
      },
      text: String,

      created: {
        type: Date,
        default: Date.now,
      },
    },
  ],
  likes: [
    {
      type: Schema.Types.ObjectId,
      refPath: "onModel",
    },
  ],
  onModel: {
    type: String,
    enum: ["User", "Imam"],
  },
});
module.exports = mongoose.model("Post", postSchema);

this is delete route function

exports.userdelete = (req, res) => {
  User.findByIdAndRemove(req.params.id).exec((err, doc) => {
    if (err) {
      return res.status(400).json({
        error: "Something went wrong",
      });
    }
    return res.json({
      message: "User deleted",
    });
  });
};
1

There are 1 best solutions below

0
Shuvro On

You Can follow this code

You can use cascade delete in mongoose

User.findOne({...}, function(err, customer) {
  Post.remove();
});