19. Database, Schema & Models | Mongoose

  • First of all create a cluster(collection of databases) on mongoDB Atlas and connect it to mongoDB compass at your computer by following these steps:-

1. Create a Cluster on MongoDB Atlas

Step 1: Sign up/Log in

Step 2: Create a Cluster

  1. After logging in, click on "Build a Cluster" or "Create a Cluster".

  2. Choose the Cluster Type: For free-tier, select Shared Cluster (M0).

  3. Select a Cloud Provider and Region:

    • Choose a cloud provider (AWS, Azure, or Google Cloud).

    • Select a region close to your application or your physical location for better performance.

  4. Configure Cluster: Leave the default settings for a free-tier cluster.

  5. Create Cluster: Click "Create Cluster" and wait for it to be provisioned (takes ~5-10 minutes).


2. Configure Cluster Access

Step 3: Add a Database User

  1. Go to the Database Access section under "Security" in the left-hand menu.

  2. Click "Add New Database User".

  3. Set:

    • Authentication Method: Username/Password.

    • Username: Create a unique username.

    • Password: Create a strong password.

  4. Assign the user role: Choose Atlas Admin (for full access during setup).

  5. Click "Add User".

Step 4: Add Your IP Address

  1. Go to the Network Access section under "Security".

  2. Click "Add IP Address".

  3. Add your local IP address:

    • To allow your current IP, click "Add Current IP".

    • To allow all IPs, enter 0.0.0.0/0 (not recommended for production).

  4. Click "Confirm".


3. Get Connection String

Step 5: Retrieve the Cluster Connection String

  1. Go to the Clusters section in Atlas.

  2. Click "Connect" for your cluster.

  3. Select "Connect using MongoDB Compass".

  4. Copy the connection string (e.g., mongodb+srv://<username>:<password>@cluster0.mongodb.net/<dbname>).

Replace <username> and <password> with the credentials you created earlier.


4. Download and Install MongoDB Compass

Step 6: Install MongoDB Compass

  1. Download MongoDB Compass from the official site.

  2. Install it by following the instructions for your operating system.


5. Connect to MongoDB Atlas using Compass

Step 7: Set up Connection in Compass

  1. Open MongoDB Compass.

  2. In the "New Connection" window:

    • Paste the connection string you copied earlier.

    • Replace <username> and <password> with your database user credentials.

  3. Click "Connect".


6. Verify Connection

After successful connection, you’ll see a list of databases in the Compass interface. You can now create, read, update, or delete documents and collections.

  • To know and set up your IP address in your network access tab in atlas in cmd write this command and press enter “curl -4 ifconfig.me“ your id will be prompted then add it to network access.

  • Now add a “config“ folder inside src folder, this config folder is for adding any configuration.

  • inside config create a file “database.js“ here we will write a logic to connect DB

  • we will use npm package known as mongoose (which is used to connect your application with mongoDB) by executing command “npm i mongoose“

      //database.js
      const mongoose = require("mongoose");
      mongoose.connect(
        "....connectionString.../dbName"
      );
    

    above is not a write way to connect DB as it return a promise and it is a async connection

    right way is this

      const mongoose = require("mongoose");
      const connectDB = async () => {
        await mongoose.connect(
          "....connectionString.../dbName(i have taken practice as database name)"// this is "cluster + dbName"
        );
      };
      connectDB()
        .then(() => {
          console.log("connected to DB");
        })
        .catch((err) => {
          console.error("not connected DB");
        });
    

    above code still doesn’t connect Why because we have to include this code inside app.js file by require(“./config/database“) and also keep in mind that right way is to first connect application to DB and then do app.listen() or start server because if we don’t do this then if someone do app.listen() or start server first, make API call from DB and still DB doesn’t connected this will be a problem.

      const mongoose = require("mongoose");
      const connectDB = async () => {
        await mongoose.connect(
          "....connectionString.../dbName"// this is "cluster + dbName"
        );
      };
      module.exports= connectDB;
    
      //app.js
      const express = require("express");
      const app = express();
      const port = 3000;
      const connectDB = require("./config/database");
      connectDB()
        .then(() => {
          console.log("connected to DB");
          app.listen(port, () => {
            console.log(`Server is running on port ${port}`);
          });
        })
        .catch((err) => {
          console.error("not ok some error");
        });
    

    in console we get

Creating Schema

  • Schema is identity for collection(table) document, it is basically about what type of information we want to store with legit field name.

  • we read schema from mongoose

  • after creating schema we create model, we can create multiple instances by using model as SchemaName. For example User table using userSchema, Friend table using same userSchema etc.

    for example:- mongoose.model(“Name of model“, SchemaName)

    mongoose.model(“user“,userSchema);//user is table name

  • name with capital letter of model name depicts model like classes.

  • Now create models folder inside src and in models create user.js schema

//user .js
const mongoose = require("mongoose");
const userSchema = new mongoose.Schema({
  firstName: {
    type: String,
  },
  lastName: {
    type: String,
  },
  email: {
    type: String,
  },
  password: {
    type: String,
  },
  City: {
    type: String,
  },
});
const User = mongoose.model("User", userSchema);
module.exports = User;
//creating schema for User table

creating a POST API to add data to Database

Note:- All the operation related to database whether it is like fetching data from database or sending data to database and many other operation are all asynchronous in nature and they return promise so always perform these operation in async…await syntax and use try….catch block to handle error gracefully.

  •     // app.js
        const express = require("express");
        const app = express();
        const port = 3000;
        const connectDB = require("./config/database"); //getting DB connection
        const User = require("./models/user"); //getting User model
        app.post("/user", async (req, res) => {// POST API to save data to DB 
          const user = new User({ ///creating a new Instance of User model
            firstName: "faraz",
            lastName: "alam",
            email: "test@123.com",
            password: "test@123",
            City: "Pune",
          });
          try {
            await user.save();
            res.send("user addedd sucessfully");
          } catch (err) {
            res.status(400).send("error saving the data:- " + err.message);
          }
        });
    
        connectDB()
          .then(() => {
            console.log("connected to DB");
            app.listen(port, () => {
              console.log(`Server is running on port ${port}`);
            });
          })
          .catch((err) => {
            console.error("Not connected to DB");
          });
    

    when “POST …/user“ get hit in postman data save to database.

  • One thing to note that in database “practice“ is database name, “users“ is collection or table name although we have created schema for “User“ table but in database database and collection name is usually stored in small and plural form. And the table like thing which have different field is called as “document“, we can create multiple documents in a “users” collection by altering data in POST API . There is unique field known as “_id“ which is created automatically by mongoDB for us, however we can also enter this “_id“ manually but it suggested by mongoDB not to do so.

Notes:- If You get this error “OPEN:SSL Internal……Port 80…..“ while sending data to database you can check out this video.