Database Connection using NODE JS example

Database Connection using NODE JS example

In my earlier article, you have learned how to create your first node js application and how to create node js web application. If you have not read it, I am suggesting you to read these two articles. Below are the link of these articles.

http://java.gunustories.com/2018/06/generate-node-js-web-application.html

After creating a web application, you need to deal with database. So before writing node js script, you need to download and install MongoDB in your PC. To download MongoDB go to the https://www.mongodb.com/download-center?jmp=nav#community link. Before start writing node js database connection, please insure that MongoDB is running in your PC.

Now  open app.js file and write below configuration to connect with MongoDB.

const MongoClient = require('mongodb').MongoClient
var db
MongoClient.connect('mongodb://localhost:27017/', (err, database) => {
  if(!err) {
    console.log("We are connected");
    db = database.db('training')
  }
})

var datafordb;
router.get('/adduser', function(req, res, next) {
   datafordb = {
    "userid": 'Demo User',
    "email": 'demouser@xyz.com',
    "password":'demo@123'
  };
  db.collection('login').save(datafordb);
  res.send('Now yor data has been saved into database');
 });


After successfully inserted data into MongoDB, you can check it by using MongoDB Compass utility. Data will be showing in below format.

MongoDB Screen
Thanks for reading this article. Please share this article if you found meaningful for you.

Comments

Recent Post

Recent Posts Widget

Popular posts from this blog

Capture image from webcam java code, examples

How to capture finger prints in java

Shallow Copy Deep Copy Java example