Let's dig deep into more functionalities in the mongo database by doing CRUD operations with our app.



Previously we discussed how to do Create and Read (fetching all products) operations

Now-> Finding one Product, Updating and Deleting will be covered

Finding One Product

IMP=> in view => need to pass the product._id

Controller

exports.getProduct = (req, res, next) => {

  const proId = req.params.productId;
  //product._id should be passed to here

  Product.findById(proId)
    .then((product) => {
      if (!product) {
        console.log("NO products Found...!!!");
        res.redirect("/products/ProductISNOTFound");
        return;
      }

      res.render("products/product-detail", {
        prod: product,
        pageTitle: "Product Details",
        active: "prod",
        hasProduct: true,
      });
    })
    .catch((err) => {
      console.log(err);
    });
}

In model

const mongoDb = require("mongodb");
//inside the Product class
 static findById(id) {
  

    const db = getDb();

    return (
      db
        .collection("products")
 
  // .find({ _id: id })
this will not work because id is a bson object type ->_id:ObjectID

        .findOne({ _id: new mongoDb.ObjectID(id) }) //this will work

        .then((product) => {
          console.log(product);
          return product;
        })
        .catch((err) => {
          console.log(err);
        })
    );
  }

Update Product

in product model

we modified it by adding an id field
Imp concept -> new mongoDb.ObjectID(null)  <- this will also return a id

class Product {
  constructor(_id, title, price, description, imgUrl) {
    this.title = title;
    this.price = price;
    this.description = description;
    this.imgUrl = imgUrl;
    this._id = _id ? new mongoDb.ObjectID(_id) : null;
  }

  save() {
    const db = getDb();
    let dbOp;
    if (this._id) {
      dbOp = db
        .collection("products")
        .updateOne({ _id: this._id }, { $set: this });
    } else {
      dbOp = db.collection("products").insertOne(this);
    }
    return dbOp
      .then((result) => {
        console.log("result=> " + result);
      })
      .catch((err) => {
        console.log(err);
      });
  }

}


in controller

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;

get the product details by post method
get the updated elements and create the instance 
when creating a normal product (not an update) pass null

  const product = new Product(
    prodId,
//now this can be directly passed and product constructor make it bson object
    uptitle,
    upprice,
    updescription,
    upimgUrl
  );
  product
    .save()
    .then((result) => {
      console.log("Updated Product...!!!");

      res.redirect("/admin/products");
    })
    .catch((err) => {
      console.log("ERROR");
    });
};


<extra><create Product>
exports.postAddProduct = (req, res, next) => {
  const title = req.body.title;
  const imgUrl = req.body.imgUrl;
  const price = req.body.price;
  const description = req.body.description;

  const product = new Product(null, title, price, description, imgUrl);
  product
    .save()
    .then((result) => {
      console.log("Succsfully addeddd..!!!!");
      res.redirect("/");
    })
    .catch((err) => {
      console.log(err);
    });
};


Delete Product

Product Model

static deleteById(id) {
    const db = getDb();

    return db
      .collection("products")
      .deleteOne({ _id: new mongoDb.ObjectID(id) })

      .then((result) => {
        console.log("Deleted");

        console.log(result);
      })
      .catch((err) => {
        console.log(err);
      });
  }

Controller

exports.postDeleteProduct = (req, res, next) => {
  const prodId = req.body.productId;

  Product.deleteById(prodId)
    .then((_) => {
      return res.redirect("/admin/products");
    })

    .catch((err) => {
      console.log("ERROR");
     
    });
};


CRUD Completed...!!!