Javascript 使用nodejs+;数据库

Javascript 使用nodejs+;数据库,javascript,node.js,mongodb,Javascript,Node.js,Mongodb,如何在mongodb上使用nodejs执行软删除 例如,使用此代码,是否可以修改为执行软删除,或者是否有其他方法 控制器/category.js exports.remove = (req, res) => { const category = req.category; category.remove((error, data) => { if (error) { return res.status(400).json({

如何在mongodb上使用nodejs执行软删除

例如,使用此代码,是否可以修改为执行软删除,或者是否有其他方法

控制器/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

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

我不确定
req.category
是模型的实例还是模型本身

所以,在我下面的回答中,我假设您以某种方式获得了模型的实例,并将其作为
req.category

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) 更改删除程序:

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)
    });
  }
};
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)
    });
  }
};
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) 更改上市程序:

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

请告诉我什么是类别的模式?软删除对你们来说意味着什么?(不要认为这是一个通用术语)。请用具体的例子说明你的期望。显示一小部分文档、一个操作以及该操作对数据的预期结果。您当前的问题对于提供的代码并没有太多解释。我们可以假定,
req.category
已经用当前的mongoose模型填充,或者可能是预先准备好的查询。但是,如果没有代码显示与路由中的
:categoryId
:userId
的任何交互,这只是*不太清楚。数据中的软删除不会从数据库中删除。数据仍然存在,但对于用户来说,它表明“项目”或类别已被删除。@Omar
req.category
不是明显的参数。是猫鼬模型吗?或者是模型实例(查询数据库的结果)?我添加的models/category.js代码列表过程不起作用。返回了一个错误,但当我运行我的列表代码时,它工作了。你知道为什么吗?@Omar修复了我忘记在req.category之前放置wait的列表代码。find@Omar请记住根据上述代码更改模式