First Steps - Install MongoDB on your Workstation

 

Click the below links to download (Choose your OS) : 

(Windows) : https://fastdl.mongodb.org/win32/mongodb-win32-x86_64-2008plus-ssl-4.0.9-signed.msi 

(Ubuntu) : https://repo.mongodb.org/apt/ubuntu/dists/xenial/mongodb-org/4.0/multiverse/binary-amd64/mongodb-org-server_4.0.9_amd64.deb

(MacOS) : https://fastdl.mongodb.org/osx/mongodb-osx-ssl-x86_64-4.0.9.tgz

(Other) : 

https://www.mongodb.com/download-center/community

After download finishes, install and make sure you run MongoDB as a service..

 

MongoDB Compass Community - Tool (skip this step, if you like to live dangerously)

 

After installation, we could download and install this handy tool called compass made for mongodb to do CRUD operations with a GUI. Mostly we'll be using to check whether data entry was successful or not.

Headover to : 

https://www.mongodb.com/download-center/compass?jmp=hero

 

Create a NodeJS project

 

Install all the required modules 

- express

- mongoose

- cors

- body-parser

Tip : You could install all the modules at a time by doing this.

npm install -save express mongoose cors body-parser

Thank me later!

 

app.js

Require all the installed modules.

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const mongoose = require('mongoose);

Now initialize express with a variable called app, and use all body-parser to intercept the params and body and convert them to a JSON file.

const app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

 Use cors to enable Cross-Origin-Requests from whitelisted domains from other applications. (use '*' to allow all domains)

app.use(cors({origin: '<domain-address-here>'}))

At last we listen to the app at port 8000.

app.listen(8000);

I'll be using Express Router to keep my code clean and readable. So create a folder called router in your project root and create a file called users.js and require mongoose and express.Router(). To know how express.Router() works, checkout my previous post : https://www.thecodingpup.com/post_detailed/maintain-nodejs-api-endpoints-using-expressrouter .

const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')

const app = express()

var users = require('.././router/users.js')

app.use('/api/users', users);

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.options('*', cors())

app.listen(8000);

users.js 

const express = require('express')
const router = express.Router()
const mongoose = require('mongoose')

Since MongoDB is running locally on our machine the connection URL is mongodb://localhost:27017/<database-name> .  To start connection to the database, initialize a variable with the connection string.

var db = mongoose.connect("mongodb://localhost:27017/mystore")

 To add data to the database, we need to specify a data model for the Mongoose ODM. So create another folder called models and create a file called schema.js

schema.js

var mongoose = require('mongoose'), Schema = mongoose.Schema;

var Users = new Schema({
    name  : {type:String,required:true},
    phone: {type:String,required:true, unique:true}
});

mongoose.model("Users",Users);

we require mongoose and schema from mongoose

we create a new schema called Users consisting of fields name,phone of a user

then we create a model from that schema by mongoose.model("Users",Users)

To use the schema in our users.js file, we need to require schema.js first which will enable us to access all the functions and classes in schema.js, we will create a get route and send data with body which will add it to the database

users.js

const schema = require('./schema.js')
const express = require('express')
const router = express.Router()
var db = mongoose.connect("mongodb://localhost:27017/mystore")

var Users = mongoose.models('Users')

To send data to database, we use the exported model of users to create new user in the database, the same applies to search data

router.post('/create',(req,res) => {
 Users.create({name:req.body.name,phone:req.body.phone}, (err,data)=>{
  if(err){
   console.log(err)
   res.json(err)
  }
 
  else {
   console.log(data)
   res.json(data)
  }
 })
})

router.get('/view',(req,res) => {
 Users.find({}, (err,data)=>{
  if(err){
   console.log(err)
   res.json(err)
  }
 
  else {
   console.log(data)
   res.json(data)
  }
 })
})

Our total code will look like this:

app.js

const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')

const app = express()

var users = require('.././router/users.js')

app.use('/api/users', users);

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.options('*', cors())

app.listen(8000);

schema.js

var mongoose = require('mongoose'), Schema = mongoose.Schema;

var Users = new Schema({
    name  : {type:String,required:true},
    phone: {type:String,required:true, unique:true}
});

mongoose.model("Users",Users);

router/users.js

const schema = require('./schema.js')
const express = require('express')
const router = express.Router()
var db = mongoose.connect("mongodb://localhost:27017/mystore")

var Users = mongoose.models('Users')

router.post('/create',(req,res) => {
 Users.create({name:req.body.name,phone:req.body.phone}, (err,data)=>{
  if(err){
   console.log(err)
   res.json(err)
  }
 
  else {
   console.log(data)
   res.json(data)
  }
 })
})

router.get('/view',(req,res) => {
 Users.find({}, (err,data)=>{
  if(err){
   console.log(err)
   res.json(err)
  }
 
  else {
   console.log(data)
   res.json(data)
  }
 })
})

module.exports = router;

Now open terminal and run the application, use a service like postman to send requests with body to localhost:8000/create and use the url localhost:8000/view to view the data. For more details/tutorials you could checkout the documentation on mongoose or ask me down in the comments below.

Happy Coding!

blog comments powered by Disqus