node.js - 无法使用 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`
})
}
})
}
解决方案
最佳实践要删除一个项目,你必须有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`
})
}
})
}
推荐阅读
- javascript - 我如何将数据从 ejs(日期选择器)传递到 js(查询 db),然后在 ejs(在标签中)中显示结果?
- javascript - 为什么表单文本输入的 parseFloat(value) 会给出 NaN?
- ios - Xcode 10.2 是否支持最新的 NativeScript?
- javascript - 有没有办法只在基于数组的 json 对象中显示选定的属性
- azure - 如何通过 API 启用/禁用项目服务
- php - iframe 嵌入视频与 php 变量作为源不工作
- python - 如何将 YAML 数据放入字典并打印某些值?PYTHON
- mysql - mysql_query 出现问题并通过 sprintf() 在其中插入变量
- c - MPEG2 传输流 PES 填充字节长度
- apache-spark - 插入 Hive 表时,Spark 进程永远不会结束