首页 > 解决方案 > 无法使用 mongodb 中的节点删除项目

问题描述

我遇到了 removeCategory 的问题,错误是该类别总是进入 if 语句,尽管我在 URL 中提供了正确的 ID,但它不会删除类别

const Category = require('../models/category')

exports.removeCategory = (req, res) => {
    const cat = req.cat
    if (!cat) {
        return res.json({
            error: true,
            message: 'no caterory found'
        })
    }
    cat.remove((err, cat) => {
        if (err) {
            res.status(400).json({
                err: "Failed to Delete Category"
            })
            res.json({
                message: `Category ${cat} deleted Successfully`
            })
        }
    })
}

标签: node.jsmongodb

解决方案


最佳实践要删除一个项目,你必须有id,你需要Model在这种情况下使用Category

你能用吗findByIdAndRemove

例如。

const Category = require('../models/category')

exports.removeCategory = (req, res) => {
    const cat = req.cat
    const id =  req.id
    if (!cat) {
        return res.json({
            error: true,
            message: 'no caterory found'
        })
    }
    Category.findByIdAndRemove(id,(err, cat) => {
        if (err) {
            res.status(400).json({
                err: "Failed to Delete Category"
            })
            res.json({
                message: `Category ${cat} deleted Successfully`
            })
        }
    })
}

推荐阅读