猫鼬findByIdAndRemove()奇怪的行为

时间:2019-08-29 04:22:33

标签: node.js mongodb 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)})
}

1 个答案:

答案 0 :(得分:0)

请尝试以下删除脚本。

正在使用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 link

中学习MEARN Stack CRUD操作