I would love to introduce mongoose package to our backend application. It is easy, fast, flexible and readable, therefore more maintainable as well. So Let's continue the rest of our journey with mongoose.



What is Mongoose

Mongoose is a MongoDB Object Document Mapping Library (ODM) designed to work in an asynchronous environment. It’s also like Sequelize ORM tool that we discussed earlier. (But here no Relations, only Documents)

core concepts=>
define
               1 schemas and models   -> User,Product

               2 instances ->const user=new User()

               3 queries ->User.find()

Official Docs ->https://mongoosejs.com


Setup with NodeJS

IMP 1st=> NO database file -> mongoose done everything
so directly go to

2nd=> App.js

const mongoose = require("mongoose");


mongoose
  .connect("mongodb://localhost:27017/nodefirst", {
    useNewUrlParser: true,
    useUnifiedTopology: true, //optional <-for depricated warninigs
  })
  .then(() => {
    app.listen(3000);
    console.log("Server running at http://127.0.0.1:3000/");
  })
  .catch((err) => {
    console.log(err);
  });



Define The Model (Schema) => product.js

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const productSchema = new Schema({
  title: {
    type: String,
    required: true,
  },
  price: {
    type: Number,
    required: true,
  },
  description: {
    type: String,
    required: true,
  },
  imgUrl: {
    type: String,
  },
});

module.exports = mongoose.model("Product", productSchema);
//Product is the collection name
//Imp -> mongoose will convert to all simple




Let’s Create a product

In the controller

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({
    title: title,
    price: price,
    description: description,
    imgUrl: imgUrl,
  });
  product
    .save() //provide by mongoose  <= very easy
    .then((result) => {
      res.redirect("/");
    })
    .catch((err) => {});
};



Display the Product

exports.getIndex = (req, res, next) => {
  Product.find()
    .then((products) => {
      res.render("shop/index", {
        prods: products,
        pageTitle: "Product List",
        hasProducts: products.length > 0,
        active: "index",
       
      });
    })
    .catch((err) => {
      console.log(err);
    });
};


More operations will be discussed on the next Episode…Till wait.!