首页 > 解决方案 > 猫鼬 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)})
}

标签: node.jsmongodbmongoose

解决方案


请尝试以下删除脚本。

它正在使用 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 操作


推荐阅读