DEV Community

Cover image for How to use mongodb in Node.js
Chetan Rohilla
Chetan Rohilla

Posted on • Edited on • Originally published at w3courses.org

How to use mongodb in Node.js

Mongodb is a NoSQL Database. The data stored in mongodb is in JSON-like Documents. The Collection in Mongodb is called a Table. In Mongodb we can create, update, delete or list the documents, projection, sort() and limit() methods, create a collection, drop collection, etc. For larger projects we can use operators, models or relationships in mongodb.

Advantages of MongoDB

  1. Document-oriented data model
  2. Code-native data access
  3. Flexible document schemas
  4. Uses internal memory for storing working sets
  5. Powerful querying and analytics
  6. Change-friendly design
  7. No complex joins
  8. MongoDB is schema less. It is a document database in which one collection holds different documents.
  9. Easy horizontal scale-out
  10. Light Weight
  11. Extremely faster than RDBMS
  12. Big and complex data can be used

Create a Node.js Project

Create a new directory and initialize node with the command npm init. Use the below commands.

mkdir helloworld
cd helloworld/
npm init -y
Enter fullscreen mode Exit fullscreen mode

Now, we can run the node.js server using the command node index.js (index.js is a file which has our all logic or codes). But when we changes our code we needs to restart the server each time. So, we can solve this problem using the node package nodemon. It automatically restarts the server when something has been changed in the code. The below command installs nodemon to our project.(-g represents that package will install globally in our machine and can be use in any project in same machine)

npm install -g nodemon
Enter fullscreen mode Exit fullscreen mode

Now, in package.json file we just need to add the code given below. So, we can start our server using npm start command.

"scripts": {
   "start": "nodemon index.js",
   "test": "echo \"Error: no test specified\" && exit 1"
},
Enter fullscreen mode Exit fullscreen mode

It’s time to install Express JS. It is an open-source web framework for node JS to handle http requests. The below command installs express to our project.

npm install express --save
Enter fullscreen mode Exit fullscreen mode

Create a file index.js which will be our bootstrap or root server file. Now paste the code given below.

var express = require('express');
var app = express();
app.get('/', function (req, res) {
  res.send('Hello World!');
});
app.listen(8000, function () {
  console.log('Listening to Port 8000');
});
Enter fullscreen mode Exit fullscreen mode

When you start the server using the command npm start you will see Hello World!.

Install and Connect Mongodb Database in Node.js

To use mongodb in our node.js project we should have MongoDB installed in our local machine or server(during deployment).

First of all, Install mongodb from MongoDB’s official website.

Now install NoSQLBooster GUI tool of MongoDB. It’s like phpmyadmin for mysql.

After installing MongoDB, install mongoose which is an Object Data Modeling library for MongoDB and Node js. It manages relationships between data and provides schema validation. Use the command below to install mongoose.

npm i mongoose
Enter fullscreen mode Exit fullscreen mode

Now we will connect mongodb to node.js with the help of mongoose. Paste the code given below in index.js file.

var express = require('express');
var app = express();
const mongoose = require('mongoose');
//Routes
app.get('/', function (req, res) {
    res.send('Hello World!');
});
//Database
mongoose.connect('mongodb://localhost/test', {useNewUrlParser: true});
mongoose.connection.once('open',function(){
    console.log('Database connected Successfully');
}).on('error',function(err){
    console.log('Error', err);
})
app.listen(8000, function () {
    console.log('Listening to Port 8000');
});
Enter fullscreen mode Exit fullscreen mode

Create Models in MongoDB to manage tables or collections

Create a folder named models and inside the models folder create user.js file. Paste the code given below in user.js file.

const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
  userName: {
    type: String,
    required: true,
  },
  userEmail: {
    type: String,
    required: true,
  },
})
module.exports = mongoose.model('User',empSchema)
Enter fullscreen mode Exit fullscreen mode

Now, we will post the JSON data to server using http request. So, to handle this in Express we will need Body-Parser. Install it with the bellow command.

npm install body-parser
Enter fullscreen mode Exit fullscreen mode

Create a route /add and handle the post request inside the callback function. To do this paste the code given below in index.js file.

var express = require('express');
var app = express();
const mongoose = require('mongoose');
const bodyParser  = require('body-parser');
require('./models/user.js');

//Routes
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', function (req, res) {
    res.send('Hello World!');
});
app.post('/add', function(req,res) {
  const user = new User({
    userName: req.body.userName,
    userEmail: req.body.userEmail,
  });
  user.save().then(val => {
    res.json({ msg: "User Added Successfully", val: val })
  })
})
//Database
mongoose.connect('mongodb://localhost/test', {useNewUrlParser: true});
mongoose.connection.once('open',function(){
    console.log('Database connected Successfully');
}).on('error',function(err){
    console.log('Error', err);
})
app.listen(8000, function () {
    console.log('Listening to Port 8000');
});
Enter fullscreen mode Exit fullscreen mode

Now send the post request to http://localhost:8000/add. If request success it will insert values to userSchema.
This tutorial was created at Nodejs with Mongodb

Find more node.js tutorials here

Top comments (2)

Collapse
 
codingtomusic profile image
Tom Connors • Edited

I have no idea how to : Now send the post request to localhost:8000/add

My repo is here, I did the whole thing but not sure how to call it github.com/coding-to-music/express...

Collapse
 
readymadecode profile image
Chetan Rohilla • Edited

Please send the post request using any frontend library like react or angular. Else just use the postman and call the api localhost:8000/add with body parameters userName, userEmail. Its very easy please use with postman to just test it. postman.com/. If using localhost You have to download postman to your windows or mac machine.

Thanks :)