Simple guide to start with NodeJs,Express and MongoDB
Hey Hey guys welcome to my first blog on NodeJs and Expressjs.In this blog i’m going to teach you how you can get started with Nodejs and i’ll also teach you how to make a simple rest api using nodejs,express and mongodb.So let’s get started.
First of all you need to download Node.js on your system.you can download it from here
You need to download the LTS version.Once the downloading finished,you need to run the setup and complete the setup guide (just click next and next).
Once you done with that and hopefully everything goes well,Let’s check the version .
open a command prompt (just press window key+r and type cmd ,hit enter).For checking the version type node -v
.Check the version for npm also (npm -v).NPM stands for Node package manager .NPM helps us to install packages that we need while building our project.
Every thing looks fine here,Lets start coding.
Create a folder in which you will be keeping all your work.Open a command prompt or terminal (if you use mac or Ubuntu).
mkdir demo //demo is the project name
cd demo
Now you are into your root folder.Now first thing first we need to create our package.json file .Type following commands in the terminal.
npm init
Then it’s gonna ask you couple of thinks ,like name of project .Just hit enter enter for now.
Now if you see your root folder has a package.json file and a package-lock.json. This package.json file will contain info about your project .You can know more about this from here
.
Now we have the package.json.Open your project in an IDE(Atom,sublime etc).Your project structure will look like this:
package.json
package-lock.json
Now lets just install couple of packages and i’ll explain you why we need these packages and what is the use of these packages:
npm install --save express body-parser mongoose
Express is the framework that we gonna use for static routing and rending of web pages and data.You can see a folder has been created in your root folder of name node_modules,this folder will contain all your packages.Now lets create our root file . Create a javascript file name index.js
Body parser will parse the data coming in your request body.
mongoose is the library that we gonna use to query the mongo database.You can learn more about mongoose from here
.
This is gonna be our main file.You can change the name also i recommend using the same name as the name of main attribute in your package.json file.
index.js
const express = require('express');
const app = express();app.set('port',process.env.PORT || 8090);app.listen(app.get('port'),()=>{
console.log(`Server listening on ${app.get('port')}`);
})
In the above code we have just included the express package and created a server.we have to set the port so that we can listen to that particular port. Currently we are listening on PORT 8090.To run this code open your terminal ,go to the current root path where your folder is located and type:
node index.js
You will see the console, your server is up and running.Open your browser and type :
localhost:8090
Your server is up and running.Open the browser and type ‘localhost:8090’.You will see nothing ,lets take care of that.
Now we are going to handle all the requests coming to our server.
index.js
const express = require('express');
const app = express();
app.set('port',process.env.PORT || 8090);app.use('/',(req,res)=>{
res.send('hello');
})app.listen(app.get('port'),()=>{
console.log(`Server listening on ${app.get('port')}`);
})
Now stop the server using Ctrl+c and type node index.js again.Now open the browser and run the localhost again ,You’ll see you get the text.This is static rendering .
Every time you change anything in your code ,you have to refresh the server yourself to reflect the changes.Let’s just make it automatically.We are going to install another package called nodemon. What its gonna do is its gonna look for any change in your folder if any change occur it gonna refresh the server automatically.
npm install -g nodemon
You can see we used -g flag to install ,that’s because we are installing it globally.Means you don’t have to install it every time you configure a new project on your system.
Now run the terminal using :
nodemon index.js
Now we don’t have to restart the server after every change.Our server is running,express is all setup ,let’s just create a api .We are going to use mongo as a database to store our data.i’m going to show you how to start creating api .We are going to make an api to store user details in our db.
you need to install mongo first.you can download it from here
.Just follow the simple steps and your are ready to go with the installation.
After you are done with installing mongodb.Open an another terminal.we are going to use two terminal one for running server and one for running mongodb.
Go to the path where the mongodb is installed(it will be in your c folder then program files) and go to bin folder(use cd command to get to the desired ath like- cd ‘c:\program files’).Type
mongod
It is gonna shut down quickly because we have to create a folder where the data needs to be stored.
Now create a folder name data
inside your C directory(if using windows).Inside data folder create another folder name db
.Now run the mongod
command again.This time it will work.
Now mongo is all setup ,server is running,Lets start with creating a simple POST api for entering users in the database
index.js
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const config = require('./config');
app.set('port',process.env.PORT || 8090);mongoose.connect(config.path); //connecting the dbapp.use('/',(req,res)=>{
res.send('hello');
})app.listen(app.get('port'),()=>{
console.log(`Server listening on ${app.get('port')}`);
})
In the above code i have included a new file config.js
in this file we are going to write our main info like Path to database,account secrets etc.
Config.js
module.exports ={
'path':'mongodb://localhost/demoDb' // demoDb is the db name
}
You need to export things if you want to use them in another files.By default mongo uses the 27017 port. you can also change that but for now lets leave it.Now our mongo is connected,server is running.Lets start with api now.You need to add some files.The new folder structure will be :
-node_modules
config.js
index.js
model.js
package.json
package-lock.json
user_action.js
index.js
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const config = require('./config');
const bodyParser = require('body-parser');
const userAction = require('./user_action');app.set('port',process.env.PORT || 8090);mongoose.connect(config.path);app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());app.post('/createUser',(req,res)=>userAction.createUser(req,res));app.listen(app.get('port'),()=>{
console.log(`Server listening on ${app.get('port')}`);
})
In the above code we have handle the post api call of url createUser
.Any api with this url like http://localhost:8090/createUser
is gonna handle by this function.In the second argument of post request we pass call a function that is defined in user_action.js
Model.js
const mongoose = require('mongoose');
const schema = mongoose.Schema;const userSchema = new schema({
firstName:{type:String,required:true},
lastName:{type:String},
email:{type:String,required:true,unique:true},
age:{type:Number},
gender:{type:String,enum:['Male','Female']},
createdAt:{type:Date,default:Date.now}
}) ;module.exports = mongoose.model('user',userSchema);
In model.js we will be creating our model for the data base.In this we have configure firstName,lastName,age,email,gender,createdAt(the time at which the user is created).Required keyword is set to true this mean this key is important while adding a new entry into the database.Type defined what type of data we are expecting form the user.In the gender field i have used enum
this means the enter value in gender key must be from these two values only otherwise the db gonna give validation error.And default keyword is used ,if now value was provided to the key its gonna take this value,in this case we have use the current date.We have used unique flags with email that means its only gonna accept unique values for email.
user_actions.js
const model = require('./model');module.exports = {
createUser : function(req,res){
var Model = new model(req.body);
Model.save((err,data)=>{
if(err)return res.json({code:400,message:"Error in creating new user"})
else
return res.json({code:201,message:"User created successfully."})})
}}
In user_action we are going to write our logic for data manipulation and all that.As you can see we have created a function that will handle the request.
In the first like we have required the schema that we have created in our model.js file. Then var Model = new model(req.body)
we have created an instance of the schema and in the next line we have use mongoose save
function to create an entry into the db.This (err,data)=>{}
is the callback function ,This is the es6 arrow function that we have used .If there occurs an error while saving this document then we can catch the err in err else we will have the result in data variable.That’s it we are done with creating our first api for creating a new user entry in the database and how you can test this thing is working .You can test your api on POSTMAN or Advance Rest Client.You can add this in your browser extensions.
We are gonna go for ARC(advance rest client) you can add this extension into your browser and then open that ,Select get from the available methods ,you can see there are couple of other methods out there.Follow the below image.
Hit send and you will get the output in the output section.Now if every thing goes well and you get code:201 in your output then we have successfully created an entry in the database.
How to check ?
Open an another terminal ,Go to the directory where you have installed mongo,like we did in case of mongod.
Now if you are in bin folder of your mongo.Type mongo
,It will give you the mongo shell.
Type show dbs
,Its gonna give you the details of all the database created.For now we need to access demoDb
as written in our config.js
file .To get into a database type
use demoDb
Now we need to see our collections.
show collections
You can see there is a collection created of name users
. This is were our user data is stored.
To access all the documents in the collections ,Type:
db.users.find().pretty()
This command will give you all the documents stores in the user collection.
If you see any documents that means we have our first entry in the database.And this is how you can use nodejs,express to store data in mongodb.
In my next blog i’m going to teach you how you can fetch data ,update data and remove data from database.Also i’m going to teach you about some commands userful commands of mongo. checkout the next blog here.
Any doubts feel free to leave a comment,You will get the response in short time.