Reputation: 105
I'm not sure what I'm doing wrong here? The GET works fine with the same info, but the DELETE keeps giving me a 500 Internal server error, and my server logs say, "StoredProduct.delete is not a function"
For the sake of this post, I'm including the GET route and GET JS below, just to show those are working, so I think my routes are set up correctly?
These are my routes
router.get('/:productID', (req, res, next) => {
StoredProduct
.findOne({
_id: req.params.productID
})
.then(product => {
res.status(201).json(product);
});
});
router.delete('/:productID', (req, res) => {
StoredProduct
.delete(req.params.productID);
res.status(204).end()
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
});
And this is my JS
$.ajax({
type: 'GET',
url: '/products/' + productID,
success: function(product) {
$editProdName.append(`${product.name}`);
$addPrice1.val(product.prices[0].price);
$addPrice2.val(product.prices[1].price);
$addPrice3.val(product.prices[2].price);
$selectedUnit.val(product.size);
}
});
$('#deleteme').on('click', function(e) {
e.preventDefault();
console.log(productID);
$.ajax({
type: 'DELETE',
url: '/products/' + productID,
success: function(){
console.log('yippee');
}
});
});
Upvotes: 1
Views: 92
Reputation: 5853
You can use mongoose.deleteOne() and search by id and delete:
router.delete('/:productID', (req, res) => {
StoredProduct
.deleteOne({ _id: req.params.productID}).then(data =>
res.status(204).end()).catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
});
Upvotes: 1
Reputation: 168
Do you use mongoose?
If so try to
StoredProduct.deleteOne({ id: req.params.productID }, function (err) {});
Also from http://api.jquery.com/jquery.ajax/:
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.
Upvotes: 1