Previously I
have discussed creating and displaying elements. Now->
Finding a
single element
With mongoose,
it’s a piece of cake.
There is a build
in findById() method.
exports.getProduct = (req, res, next) => {
const proId = req.params.productId;
Product.findById(proId)
.then((product) => {
if (!product) {
console.log("NO products
Found...!!!");
res.redirect("/products/ProductIsNotFoundPage");
return;
}
res.render("shop/product-detail", {
prod: product,
pageTitle: "Product Details",
active: "prod",
hasProduct: true,
});
})
.catch((err) => {
console.log(err);
});
Update a Product
Very easy
with findById() and save() methods.
This save() method automatically
updates to new requests.
exports.postEditProduct = (req, res, next) => {
const prodId = req.body.productId;
const uptitle = req.body.title;
const upimgUrl = req.body.imgUrl;
const upprice = req.body.price;
const updescription = req.body.description;
Product.findById(prodId)
.then((product) => {
product.title = uptitle;
product.price = upprice;
product.description = updescription;
product.imgUrl = upimgUrl;
return product.save();
})
.then((result) => {
res.redirect("/admin/products");
})
.catch((err) => {});
};
Deleting
a Product
Freaking awesome
->findByIdAndRemove() 😋
exports.postDeleteProduct = (req, res, next) => {
const prodId = req.body.productId;
Product.findByIdAndRemove(prodId)
.then(() => {
return res.redirect("/admin/products");
})
.catch((err) => {});
};

0 Comments