TypeError: Cannot read property 'price' of undefined
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!

javascript node.js
add a comment |
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!

javascript node.js
1
Add check thatproductandupdateProductsare actually not null before callingfs.writeFile()?
– Stefan Becker
Jan 19 at 9:19
1
products.find(prod => prod.id == id)is returning undefined. Replace it with thisproducts.find(console.log)to log each product (will also returned nothing). Also, log the product ID beforegetProductsFromFile. From there you can ensure the ID you expect is passed, and check that it exists in the logs of each product.
– Callam
Jan 19 at 9:20
Mr. Stefan Becker I addedif(product) { console.log('products:',product); Cart.deleteProduct(id, product.price, callback); }the undefined output is gone. But application is still crashing!
– S. Farooq
Jan 19 at 9:27
Mr. Callam I did what you told. It returns the correct id! :(
– S. Farooq
Jan 19 at 9:31
add a comment |
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!

javascript node.js
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!

javascript node.js
javascript node.js
edited Jan 19 at 9:19
S. Farooq
asked Jan 19 at 9:15
S. FarooqS. Farooq
52110
52110
1
Add check thatproductandupdateProductsare actually not null before callingfs.writeFile()?
– Stefan Becker
Jan 19 at 9:19
1
products.find(prod => prod.id == id)is returning undefined. Replace it with thisproducts.find(console.log)to log each product (will also returned nothing). Also, log the product ID beforegetProductsFromFile. From there you can ensure the ID you expect is passed, and check that it exists in the logs of each product.
– Callam
Jan 19 at 9:20
Mr. Stefan Becker I addedif(product) { console.log('products:',product); Cart.deleteProduct(id, product.price, callback); }the undefined output is gone. But application is still crashing!
– S. Farooq
Jan 19 at 9:27
Mr. Callam I did what you told. It returns the correct id! :(
– S. Farooq
Jan 19 at 9:31
add a comment |
1
Add check thatproductandupdateProductsare actually not null before callingfs.writeFile()?
– Stefan Becker
Jan 19 at 9:19
1
products.find(prod => prod.id == id)is returning undefined. Replace it with thisproducts.find(console.log)to log each product (will also returned nothing). Also, log the product ID beforegetProductsFromFile. From there you can ensure the ID you expect is passed, and check that it exists in the logs of each product.
– Callam
Jan 19 at 9:20
Mr. Stefan Becker I addedif(product) { console.log('products:',product); Cart.deleteProduct(id, product.price, callback); }the undefined output is gone. But application is still crashing!
– S. Farooq
Jan 19 at 9:27
Mr. Callam I did what you told. It returns the correct id! :(
– S. Farooq
Jan 19 at 9:31
1
1
Add check that
product and updateProducts are actually not null before calling fs.writeFile()?– Stefan Becker
Jan 19 at 9:19
Add check that
product and updateProducts are actually not null before calling fs.writeFile()?– Stefan Becker
Jan 19 at 9:19
1
1
products.find(prod => prod.id == id) is returning undefined. Replace it with this products.find(console.log) to log each product (will also returned nothing). Also, log the product ID before getProductsFromFile. From there you can ensure the ID you expect is passed, and check that it exists in the logs of each product.– Callam
Jan 19 at 9:20
products.find(prod => prod.id == id) is returning undefined. Replace it with this products.find(console.log) to log each product (will also returned nothing). Also, log the product ID before getProductsFromFile. From there you can ensure the ID you expect is passed, and check that it exists in the logs of each product.– Callam
Jan 19 at 9:20
Mr. Stefan Becker I added
if(product) { console.log('products:',product); Cart.deleteProduct(id, product.price, callback); } the undefined output is gone. But application is still crashing!– S. Farooq
Jan 19 at 9:27
Mr. Stefan Becker I added
if(product) { console.log('products:',product); Cart.deleteProduct(id, product.price, callback); } the undefined output is gone. But application is still crashing!– S. Farooq
Jan 19 at 9:27
Mr. Callam I did what you told. It returns the correct id! :(
– S. Farooq
Jan 19 at 9:31
Mr. Callam I did what you told. It returns the correct id! :(
– S. Farooq
Jan 19 at 9:31
add a comment |
1 Answer
1
active
oldest
votes
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);
}
});
}
})
}
I added the callback belowconsole.log('deleteById: Product not found', { id }); callback();to redirect and that did it! Thanks :)
– S. Farooq
Jan 19 at 9:48
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54265622%2ftypeerror-cannot-read-property-price-of-undefined%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
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);
}
});
}
})
}
I added the callback belowconsole.log('deleteById: Product not found', { id }); callback();to redirect and that did it! Thanks :)
– S. Farooq
Jan 19 at 9:48
add a comment |
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);
}
});
}
})
}
I added the callback belowconsole.log('deleteById: Product not found', { id }); callback();to redirect and that did it! Thanks :)
– S. Farooq
Jan 19 at 9:48
add a comment |
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);
}
});
}
})
}
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);
}
});
}
})
}
edited Jan 19 at 9:52
answered Jan 19 at 9:39
CallamCallam
8,31821824
8,31821824
I added the callback belowconsole.log('deleteById: Product not found', { id }); callback();to redirect and that did it! Thanks :)
– S. Farooq
Jan 19 at 9:48
add a comment |
I added the callback belowconsole.log('deleteById: Product not found', { id }); callback();to redirect and that did it! Thanks :)
– S. Farooq
Jan 19 at 9:48
I added the callback below
console.log('deleteById: Product not found', { id }); callback(); to redirect and that did it! Thanks :)– S. Farooq
Jan 19 at 9:48
I added the callback below
console.log('deleteById: Product not found', { id }); callback(); to redirect and that did it! Thanks :)– S. Farooq
Jan 19 at 9:48
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54265622%2ftypeerror-cannot-read-property-price-of-undefined%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
Add check that
productandupdateProductsare actually not null before callingfs.writeFile()?– Stefan Becker
Jan 19 at 9:19
1
products.find(prod => prod.id == id)is returning undefined. Replace it with thisproducts.find(console.log)to log each product (will also returned nothing). Also, log the product ID beforegetProductsFromFile. From there you can ensure the ID you expect is passed, and check that it exists in the logs of each product.– Callam
Jan 19 at 9:20
Mr. Stefan Becker I added
if(product) { console.log('products:',product); Cart.deleteProduct(id, product.price, callback); }the undefined output is gone. But application is still crashing!– S. Farooq
Jan 19 at 9:27
Mr. Callam I did what you told. It returns the correct id! :(
– S. Farooq
Jan 19 at 9:31