Creating Mongoose Model And Making MongoDB Connection For Storing Our Todos

Creating Mongoose Model And Making MongoDB Connection For Storing Our Todos

In this section, we will create a Mongoose model for our Todo app. If you don't know what is Mongoose, how to create a schema and model using it, refer to this tutorial to know more.

So before connecting with the MongoDB database we need to structure how we are going to model our data for todo. In our case which fields we will need to store the information about a todo task.

Task model

  • taskID - to uniquely identify the task

  • description - to store description about a task

  • completed - this will hold boolean value and it will help us to determine whether the task is completed or uncompleted

These fields are sufficient for a basic todo app to store information about a task, we can easily perform CRUD operation on this model.

So we have finalized the fields for our model, so now let's move ahead and create our mongoose schema model.

Mongoose Schema Model

Mongoose is an Object Data Modeling (ODM) library for MongoDB and Node.js. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB.

I know the definition would not have made much sense to you so let me explain it to you in simple words.

Mongodb is schema less database so to enforce a definite schema on the database mongoose is used, along with the power of noSQL, it has in-built validation, we can define on our schemas.

To learn more about mongoose checkout this tutorial here.

Creating Todo Model

Model is an object representation of data in the database.

Install following packages:

npm install mongoose uniquid

We had installed the mongoose and uniquid packages to generate unique ids for taskID.

So, Let's create a file models/todo.js with the content:

// import mongoose
const mongoose = require("mongoose");

// reference to Schema from mongoose
const Schema = mongoose.Schema;

// creating and defining the schema
const todoSchema = new Schema(
{

  taskID: {

    type: String,

    required: true,

  },

  description: {

    type: String,

    required: true,

  },

  completed: {

    type: Boolean,

    default: false,

  },

},

{

  timestamps: true,

}

);

// use the schema to create a model
var Todos = mongoose.model("Todo", todoSchema);

// export the Todos model to use inside other modules(js files)
module.exports = Todos;

So now our Todo model is ready we can now move on to make a database connection with the MongoDB for that we are going to use MongoDB Atlas.

Making Database Connection​​

Now follow the steps in this blog and get the database url which will look like this:

mongodb+srv://sample_user:<password>@my-sample-cluster-b3ugy.mongodb.net/<dbname>?retryWrites=true&w=majority

Now, Add the below line in the .env file, complete the database string with your passwordand database name

DATABASE_URL=mongodb+srv://sample_user:<password>@my-sample-cluster-b3ugy.mongodb.net/<dbname>?retryWrites=true&w=majority

Updated .env

.env

PORT=3000

DATABASE_URL=mongodb+srv://sample_user:<password>@my-sample-cluster-b3ugy.mongodb.net/<dbname>?retryWrites=true&w=majority

Making Database Connection

Open app.js file

Import mongoose

const mongoose = require("mongoose");

Add this line below where PORT is defined:

const dbURI = process.env.DATABASE_URL;

now create a database connection

// making database object 
const connect = mongoose.connect(dbURI, {

  useNewUrlParser: true,

  useUnifiedTopology: true,

});

// connecting with database
connect.then(

  (db) => {

    console.log("Connected Successfully to Mongodb Server");

  },

  (err) => {

    console.log(err);
  }

);

Update app.js

// import express
const express = require("express");

//import mongoose
const mongoose = require("mongoose");

// import dotenv
const dotenv = require("dotenv");

// load environment variable
dotenv.config({ path: ".env" });

// read env variable using process.env.<your_env_variable_name>

const PORT = process.env.PORT;
const dbURI = process.env.DATABASE_URL;

// making connection object

const connect = mongoose.connect(dbURI, {

  useNewUrlParser: true,

  useUnifiedTopology: true,

});

// connecting with database
connect.then(
  (db) => {

    console.log("Connected Successfully to Mongodb Server");

  },

  (err) => {

    console.log(err);

  }

);

// initialize express app
const app = express();

// sending a hello response on visiting http://localhost:3000/
app.get("/", (req, res) => {

  res

    .status(200)

    .json({ message: "Hi I am Server", data: "no data on this endpoint" });

});

// listening for any HTTP requests on PORT 3000
app.listen(PORT, () => {

  console.log(`Server is running at http://localhost:${PORT}`);

});

Restart your server and you should see the following output in your terminal:

Output:

Server is running at http://localhost:3000

Connected Successfully to Mongodb Server

Now we are successfully connected with the database and now we can move on to create routes and controllers.