首页 > 解决方案 > 在删除 mongodb 和 nodejs 中的相应用户之前,删除与用户相关的博客文章

问题描述

当我删除用户时,我还想删除与该用户相关的所有博客文章。我使用了 MongoDB 的 pre() 中间件。当它被触发时,它只在帖子中将postedBy属性设置为null,然后MongoDB罗盘postedBy仍然存在以及userId这里是用户模式。

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);

这是 Post 架构

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);

这是删除路线功能

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",
    });
  });
};

标签: node.jsmongodbmongoosemongoose-schemamongoose-middleware

解决方案


您可以按照此代码

您可以在猫鼬中使用级联删除

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

推荐阅读