Reputation: 218
I am creating an online shop for learning node.js. When I delete a product from products.json file, respective products in the cart.json are also deleted. I get the following error in the picture when I try to delete a product. This is the code!
In products.ejs
<form action="/admin/delete-product" method="POST">
<input type="hidden" name="productId" value="<%=product.id%>">
<button class="btn" type="submit">Delete</button>
</form>
After linking controller, in the controller function I have In admin.js controller,
// import product model
const Product = require('../models/product');
// delete a product
exports.postDeleteProduct = (req, res) => {
const prodId = req.body.productId;
Product.deleteById(prodId, () => {
res.redirect('/admin/products');
});
}
Then in the product.js model, I have
// import cart model
const Cart = require('./cart');
// get all the products from the file
const getProductsFromFile = cb => {
fs.readFile(p, (err, fileContent) => {
if (err) {
cb([]);
} else {
cb(JSON.parse(fileContent));
}
});
};
// delete by id
static deleteById(id, callback) {
getProductsFromFile(products => {
const product = products.find(prod => prod.id == id);
const updatedProducts = products.filter(prod => prod.id !== id);
fs.writeFile(p, JSON.stringify(updatedProducts), err => {
if (!err) {
console.log('Product: ',product);
//also delete in the cart
Cart.deleteProduct(id, product.price, callback);
}
})
})
}
Upon executing the code, I get the following error. Notice, how there are two console outputs for 'Product'. One for the actual Product and second undefined
for some reason!
Upvotes: 0
Views: 890
Reputation: 11539
static deleteById(id, callback) {
console.log('deleteById', { id });
getProductsFromFile(products => {
let deletedProduct = null;
let updatedProducts = [];
for(const product of products) {
if(product.id === id) {
deletedProduct = product
} else {
updatedProducts.push(product);
}
}
if (!deletedProduct) {
console.log('deleteById: Product not found', { id });
callback();
} else {
fs.writeFile(p, JSON.stringify(updatedProducts), err => {
if (!err) {
console.log('deleteById: Product', deletedProduct);
Cart.deleteProduct(id, deletedProduct.price, callback);
}
});
}
})
}
Upvotes: 1