TypeError: Cannot read property 'price' of undefined












0















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!



enter image description here










share|improve this question




















  • 1





    Add check that product and updateProducts are actually not null before calling fs.writeFile()?

    – Stefan Becker
    Jan 19 at 9:19








  • 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













  • 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
















0















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!



enter image description here










share|improve this question




















  • 1





    Add check that product and updateProducts are actually not null before calling fs.writeFile()?

    – Stefan Becker
    Jan 19 at 9:19








  • 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













  • 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














0












0








0








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!



enter image description here










share|improve this question
















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!



enter image description here







javascript node.js






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 19 at 9:19







S. Farooq

















asked Jan 19 at 9:15









S. FarooqS. Farooq

52110




52110








  • 1





    Add check that product and updateProducts are actually not null before calling fs.writeFile()?

    – Stefan Becker
    Jan 19 at 9:19








  • 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













  • 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














  • 1





    Add check that product and updateProducts are actually not null before calling fs.writeFile()?

    – Stefan Becker
    Jan 19 at 9:19








  • 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













  • 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








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












1 Answer
1






active

oldest

votes


















1














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);
}
});
}
})
}





share|improve this answer


























  • 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











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
});


}
});














draft saved

draft discarded


















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









1














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);
}
});
}
})
}





share|improve this answer


























  • 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
















1














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);
}
});
}
})
}





share|improve this answer


























  • 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














1












1








1







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);
}
});
}
})
}





share|improve this answer















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);
}
});
}
})
}






share|improve this answer














share|improve this answer



share|improve this answer








edited Jan 19 at 9:52

























answered Jan 19 at 9:39









CallamCallam

8,31821824




8,31821824













  • 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

















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


















draft saved

draft discarded




















































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.




draft saved


draft discarded














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





















































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







Popular posts from this blog

Callistus III

Ostreoida

Plistias Cous