奇怪的行为"/>
猫鼬 findByIdAndRemove() 奇怪的行为
我正在使用 mongoose,当我尝试使用像
.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操作更多推荐
猫鼬 findByIdAndRemove() 奇怪的行为
发布评论