猫鼬 findByIdAndRemove() 奇怪的行为

编程入门 行业动态 更新时间:2024-10-04 05:24:37

猫鼬 findByIdAndRemove() <a href=https://www.elefans.com/category/jswz/34/1768566.html style=奇怪的行为"/>

猫鼬 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() 奇怪的行为

本文发布于:2024-05-30 23:29:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1771041.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:奇怪   猫鼬   findByIdAndRemove

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!