简体   繁体   English

使用 nodejs + mongodb 软删除

[英]Soft delete using nodejs + mongodb

How do i perform a soft delete using nodejs on mongodb如何在 mongodb 上使用 nodejs 执行软删除

for example using this code, can it be modified to do a soft delete instead or is there another way?例如使用此代码,可以修改它以进行软删除还是有其他方法?

Controllers/ category.js控制器/ category.js

exports.remove = (req, res) => {
    const category = req.category;
    category.remove((error, data) => {
        if (error) {
            return res.status(400).json({
                error: errorHandler(error)
            });
        }
        res.json({
            message: "Category deleted"
        });
    });
};

routes/category.js路线/category.js

const express = require("express");
const router = express.Router();

const { create, categoryById, read, update, remove, list } = require("../controllers/category");
const { requireSignin, isAuth, isAdmin } = require("../controllers/auth");
const { userById } = require("../controllers/user");

router.get("/category/:categoryId", read);
router.post("/category/create/:userId", requireSignin, isAuth, isAdmin, create);
router.put("/category/:categoryId/:userId", requireSignin, isAuth, isAdmin, update);
router.delete("/category/:categoryId/:userId", requireSignin, isAuth, isAdmin, remove);
router.post("/categories", list);

router.param("categoryId", categoryById);
router.param("userId", userById);

module.exports = router;

models/category.js模型/category.js

const mongoose = require("mongoose");

const categorySchema = new mongoose.Schema(
    {
        name: {
            type: String,
            trim: true,
            required: true,
            maxlength: 32
        }
    },
    { timestamps: true }
);

module.exports = mongoose.model("Category", categorySchema);

I'm not sure req.category is instance of model or model itself.我不确定req.category是 model 或 model 本身的实例。

So in my answer below I assume that somehow You've got instance of model and injected it as req.category因此,在我下面的回答中,我假设您以某种方式获得了 model 的实例并将其作为req.category注入

1) Add deleted field to schemas where You want to have soft delete: 1) 将已删除字段添加到要进行软删除的架构中:

const mongoose = require("mongoose");
const {Schema} = mongoose;

const categorySchema = new Schema(
    {
        name: {
          type: Schema.Types.String,
          trim: true,
          required: true,
          maxlength: 32
        },

        // deleted flag for soft delete feature
        deleted: {
          type: Schema.Types.Boolean,
          index: true,
          default: false
        }
    },
    { timestamps: true }
);

module.exports = mongoose.model("Category", categorySchema);

2) Change delete procedure: 2) 更改删除程序:

module.exports.remove = async (req, res) => {
  try {
    const category = req.category; // if it's an instance of model
    // or if it's mongoose model comment line above
    // const category = await req.category.findOne({
    //                                     _id: req.params.categoryId,
    //                                     deleted: false
    //                                   });

    if (!category || category.deleted === true) {
      return res.status(404).json({
        error: 'Requested category does not exist'
      });
    }

    category.deleted = true;
    await category.save();

    res.status(200).json({
      message: "Category deleted"
    });
  }
  catch (error) {
    res.status(400).json({
      error: errorHandler(error)
    });
  }
};

3) Change category read route: /category/:categoryId handler: 3) 更改类别读取路径: /category/:categoryId处理程序:

module.exports.read = async (req, res) => {
  try {
    const category = req.category; // if it's an instance of model
    // or if it's mongoose model comment line above
    // const category = await req.category.findOne({
    //                                     _id: req.params.categoryId,
    //                                     deleted: false
    //                                   });

    if (!category || category.deleted === true) {
      return res.status(404).json({
        error: 'Requested category does not exist'
      });
    }
    res.status(200).json(category);
  }
  catch (error) {
    res.status(400).json({
      error: errorHandler(error)
    });
  }
};

4) Change listing procedure: 4) 变更上市程序:

module.exports.list = async (req, res) => {
  try {
    const categories = await req.category.find({deleted: false});
    res.status(200).json({categories});
  }
  catch (error) {
    res.status(400).json({
      error: errorHandler(error)
    });
  }
};

Step 1: Add a new field in your Schema "Deleted" with type Boolean and Default value 'false'第 1 步:在“已删除”模式中添加一个新字段,类型为 Boolean,默认值为“false”

deleted: { type: Boolean, default: false }

Step 2第2步

Change Delete Process To:
router.delete('/:id', verifyTokenAndAuthorization, async (req, res) => {
  try {
    await User.findByIdAndUpdate(req.params.id, { deleted: true }); <= change delete status to 'true'
    res.status(200).json('user Deleted');
  } catch (error) {
    res.status(500).json(error)
  }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM