DAOs,Controllers,routes and schemas in node.js using mongodb

DAOs,Controllers,routes and schemas in node.js using mongodb

·

5 min read

In programming organization is of utmost importance because it helps the programmer or someone else understand a project's code and easily navigate through it. Today I will be talking about some of the structures used for organization in the world of software development. 1.Routes: The routes folder is usually used for grouping routes with an identical path together. The process of route creation in node is as follows

  1. Create a folder called Routes
  2. Name the route file in accordance with it's purpose, for example: user.routes.js. This means that the routes stored in this file are the user routes.
    const path=require('path');
    const userController=require(path.join(__dirname,'..','Controller','userController');
    const express=requires('express')
    const userRouter=express.Router();
    userRouter.get('/users',userControlller.getUser);
    userRouter.patch('/users/:id',user Controller.updateUser);
    module.exports={
    userRouter
    };
    
    Go into your server file and write down the code below:
    const path=require('path');
    const {userRouter}=require(path.join(__dirname,'.','Routes','user.route.js'));
    const express=require('express');
    const app=express();
    app.use(userRouter);
    
    Code explanation
    The path package is inbuilt into node.js and doesn't need to be installed through npm(node package manager) you just have to require it.
    The second line requires and run the user's controller file.
    The third line requires express which is a third-party library.
    The fourth line creates a new router object which is used in place of the app function for route registration.
    userRouter.get('/users/:id', userController.specificUser);
    Or
    app.get('/users/:id',userController.specificUser);
    
    The last line exports the router so it can be accessed from other files or folders.
    Each routes used within your project should be exported and imported into your server file(the file containing your server code) inorder for the server to be able to access those routes.
    The last line within the server file which reads
    app.use(userRouter);
    
    Instructs the server to use the userRouter
  3. Controller
    The controller serves as a middleman between the view(what your end user sees) and the model(the file that communicates with your database).
    It helps separate the business logic from the route file.
    Controller-Creation
  4. Create a folder named Controller
  5. Create a file within this folder and name the Controller file in accordance with it's purpose, for example: user.controller.js. This means that the functions stored in this file are associated with the user.
  6. Write the code below within the file.
const path=require ('path');
const {User}=require(path.join(__dirname,'..','Model','user.model');
Function getUser(req,res){
const emailAddress=req.body.email;
User.findOne({email:emailAddress},function((error,result){
If(error){
console.log(error);
}else if(result){
res.status(200).Json(result)
}
}
module.exports={
getUser
};

The code on line five communicates with the User Model and asks to find a document within the database with an email similar to the one submitted by the user through a post/put/patch/delete request.
The code on line four accessed the value submitted as an email by the user.
On the frontend a field with the name email is expected to exist.
Browser

<form action='/user' method='post'>
<input type='email' name='email' placeholder='faith@gmail.com'>
<Button type='submit'>Submit</Button>
</form>


On applications like postman
Postman is a handy application used for testing apis without created a UI like the form submitted through the browser

{
"email":"john@gmail.com",
"name":"John",
}

The format used above is called a Json format, it's used over the internet for transferring data from one source to a destination over http/https protocol
A protocol is simply an agreed upon language used for communication over the internet. Imagine visiting a country like France and communicating in Hindi with a French instead of communicating in French, the person you are communicating with might end up not understanding what you are trying to pass across because you didn't follow the agreed upon language (protocol) likewise resources on the internet "the communication between the client and server"
The client is the resource requesting for data for example your browser or an application such as postman
The server is the resource which stores and awaits request from the client, it's basically a store with a seller where and individual comes to buy goods from.
The storage is the server
The buyer is the client
The seller is an API(application programming Interface).It serves a middleman between the server and Client, it lists out the resources the client can access on the server.(like the menu and the waiter in a restaurant telling the customer what they have to offer.
SCHEMAS
A schema is simply the structure of your database, the structure which the data going into your database should take.
Model or DAOs
A model or DAOs(data access objects) is an abstraction that represents a table/data/collection in your database.

Schema and Model creation
const mongoose=require ('mongoose');
const userSchema=new mongoose.Schema({
name:{
type:String,
required:true
},
email:{
type:String,
required:true
},
firstName:{
type:String,
required:true
}
});
const User=mongoose.model('User',userSchema);
module.exports={
User
}

Code explanation
Line one requires the mongoose package which helps us communicate easily with the database, if you are familiar with the Laravel framework then you would have heard of Eloquent which serves the same purpose but for PHP's Laravel.
Without requiring mongoose we won't be able to create the data schema because the data schema object comes from mongoose.
Line two creates an instance of the mongoose's schema
The sub objects within the schema instances defines the fields and the information about those fields.

name:{
type:String,
required:true
},

States that a field assigned the label "name" will exist within the database and will be of type String and is required (cannot be null)
The last line is the model creation code,in mongoose we create a model by writing

const variable=mongoose.model(model name, schema to be used by the model);


I stored the created model in a variable so I can easily export it out of the module. Mongoose model naming convention In mongoose the model is usually capitalized and in it's singular form, mongodb will take this name convert it into lowercase and pluralize it so as to form the collection name. For example creating a user model will follow this syntax in mongoose:

const User=mongoose.schema('User', userSchema);

Mongodb will take this name and convert it into

users

The second parameter passed into the mongoose.model function is the schema which the user model will conform to, This means that documents stored within the user's collection using the user model will follow the structure defined in the userSchema.
I hope this article was helpful to you, please leave a like or comment.
Thanks for reading.