Node.jsTechnical NewsWeb Socket

Connect Web Socket Server to Mongo DB using Mongoose Clien

In this web guide, you will learn how to connect web socket server to Mongo DB using Mongoose library. Before starting you must set up your web socket server. If you do not know how to setup web socket server then visit here. You can also connect to database without using mongoose.

Steps to connect web socket server to Mongo DB

Before starting close your server and then follow the steps below

  1. Open folder that contain index.js file related to your server.
  2. Press Shift + Right Click  then click on “open command window here” as show below
  3. Once command promp is open type command “npm install mongoose”  without quotes and hit enter as shown below
    Install Mongoose Using Node.js
  4. Wait for installation, once finished close cmd window.
  5. Now open index.js file in any editor you like  then copy and paste below code
    //Calling Express Library
    var app = require('express')();
    
    //Calling http library
    var http = require('http').Server(app);
    
    //Calling Socket.io Library
    var io = require('socket.io')(http);
    
    //Calling Mongoose Library
    var mong_oose = require('mongoose');
     
    io.on('connection', function(socket){
       console.log("Server is running");
    });
    
    http.listen(3001, function(){
      console.log('listening on *:3001');
    });
    
    
    
    var dbURI = 'mongodb://localhost:27017/db3000'; 
     
    mongoose.Promise = global.Promise; 
    // Create the database connection 
    mongoose.connect(dbURI, { useMongoClient: true }); 
    
    //If connected
    mongoose.connection.on('connected', function () {     
      console.log('Mongoose default connection open to ' + dbURI);
    }); 
    
    
    
    // If the connection throws an error
    mongoose.connection.on('error',function (err) { 
      db_connection = "No"; 
      console.log('Mongoose default connection error: ' + err);
    }); 
    
    // When the connection is disconnected
    mongoose.connection.on('disconnected', function () { 
      db_connection = "No"; 
      console.log('Mongoose default connection disconnected'); 
    }); 
    
    //When connection is terminated
    process.on('SIGINT', function() {  
      mongoose.connection.close(function () {    
        console.log('Mongoose default connection disconnected through app termination'); 
        process.exit(0); 
      }); 
    });
  6. Save file and open command prompt in same folder as mention in step 2.
  7. After that run command “node index.js” as shown below
    Mongo DB Connection using Mongoose
  8. Before executing above command make sure that mongo db is running. If database is not running then exit cmd and start mongodb. After open command prompt again. If you have not installed mongo database then please visit here.

 

Libraries Used

In above code, 4 node.js libraries are used that are

  1. Express – that can be install with command npm install express
  2. Http : that can be install with command npm install http
  3. Socket.io : that can be install with command npm install socket.io
  4. MongooseJS : installation is mentioned in above code.

For installing libraries just open command prompt in same folder then execute them.

Brief explanation about code

In above code 4 libraries are  included i.e Express, http, socket.io and mongoose as mention above. After that server is connection is made using socket.io library as shown below

//Calling Express Library
var app = require('express')();

//Calling HTTP Library
var http = require('http').Server(app);

//Calling Socket.io Library
var io = require('socket.io')(http);

//Calling Mongoose Library.
var mongoose = require('mongoose');
io.on('connection', function(socket){
   console.log("Server is running");
});

http.listen(3001, function(){
  console.log('listening on *:3001');
});

You can see that server is running on port 3001. After that a variable is defined with name dbURI in which database url is defined. Then we configure database connection. After that we check for database connection as shown below

var dbURI = 'mongodb://localhost:27017/db3000'; 
mongoose.Promise = global.Promise; 

// Create the database connection 
mongoose.connect(dbURI, { useMongoClient: true }); 

//If connected
mongoose.connection.on('connected', function () {     
  console.log('Mongoose default connection open to ' + dbURI);
}); 



// If the connection throws an error
mongoose.connection.on('error',function (err) { 
  db_connection = "No"; 
  console.log('Mongoose default connection error: ' + err);
}); 

// When the connection is disconnected
mongoose.connection.on('disconnected', function () { 
  db_connection = "No"; 
  console.log('Mongoose default connection disconnected'); 
}); 

//When connection is terminated
process.on('SIGINT', function() {  
  mongoose.connection.close(function () {    
    console.log('Mongoose default connection disconnected through app termination'); 
    process.exit(0); 
  }); 
});

You can see different message when connection is connected, terminated, disconnected and get error.

Why to Use Mongoose ?

Mongoose is very simple to use as compared to java script default functions. You can use schema to define collections that is more secure then using java script default. With the help of mongoose you can shorten your codes for saving data as compared to java script default. This is main reason to use mongoose rather then java script default.

If  you are facing some problem in connecting database then comment down below. All code mention above is tested on windows operating system but you use same commands on Apple and others OS.

How to save data using Mongoose ?

It is very simple to save data using Mongoose then java script default. Just your collection schema then save the data using save command. Below is simple example to call schema then save data in database.

//Mongoose Schema 
var Schema = mongoose.Schema;


//Users Schema
var userSchema = new Schema({
  	email : String,
	isAlive : Boolean
});


var userdata = new User({
	email : "Your Email", 
	isAlive : true
});

userdata.save(function (err, data) {
    if(err)
    {
        //Cannot save data
    } else {
        //Data saved
    }
});

Call mongoose schema and then define collection schema as mention above. After that pass data as in schema and save it as shown above. It is not mandatory to use schema but it just add security.

Tags

Anil Mehra

I am Anil Mehra, a passionate, workaholic and a Full Stack Tech Savvy Programmer with true north towards growth. I have worked on 256 live projects in MNC. I am expertise in the field of Programming, Server Management, SEO, Blogging and SMO...

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button