node.js - 猫鼬 findByIdAndRemove() 奇怪的行为
问题描述
我正在使用猫鼬,当我尝试使用查询时,.findByIdAndRemove()
它删除了内容但没有从数据库中删除产品,它只是将其转换为Null
喜欢
{"_id":"5d67502aaffb3729a0e24904","name":null,"image":null,"price":null,"desc":null,"__v":0}
形式
<form action='/product/<%=product._id%>' method="POST">
<button type="submit" class="btn btn-danger">Delete</button>
</form>
//Route
router.post('/product/:productId',productController.deleteProduct)
//controller
//delete product
exports.deleteProduct = (req, res, next)=>{
const prodId = req.params.productId
Product.findByIdAndRemove(prodId)
.then(() =>{
console.log('has been deleted')
res.redirect('/product')
})
.catch(err=>{console.log(err)})
}
解决方案
请尝试以下删除脚本。
它正在使用 id 被一个文档删除
Product.remove({_id : new mongoose.Types.ObjectId(prodId)}, (err, result) => {
if(err) console.log(err);
else console.log(result)
})
它正在通过 _id 删除文档
Product.findByIdAndRemove(prodId, (err, result) => {
if(err) console.log(err);
else console.log(result)
})
它被一个文件删除
Product.remove({name: 'yourName'}, (err, result) => {
if(err) console.log(err);
else console.log(result)
})
或其他选择
Product.deleteOne({ name: 'Eddard Stark' }, callback);
在路由器中
router.delete('/product/:productId',productController.deleteProduct)
在前端,您调用删除 API。如果有兴趣可以在GitHub 链接中学习 MEARN Stack CRUD 操作
推荐阅读
- python - 如何在 Google Cloud Composer 工作节点上更新 gcloud?
- python - Django没有在模板中呈现python变量
- visual-studio - How to add Auto Brackets in Visual studio Code like in JetBrains IDE?
- c - 如何用const代替#define实现#include判断?
- azure - 用于顺序访问的 Cosmos DB 分区键和查询设计
- c++ - 无法编译 Modelica 程序,因为已达到数组的最大内存分配(编译器堆空间不足)
- python - 获得真正基本烧瓶的 404 错误
- ios - 回到某个viewController
- javascript - 如何将 npm 包导入客户端文件
- c++ - 转换向量
到 char ** 数组?