whathetech Database,Mongodb,node.js MongoDB with Nodejs using Mongoose – Connection

MongoDB with Nodejs using Mongoose – Connection

MongoDB is an opesource document database. To being, goto https://docs.mongodb.com/manual/installation/ and follow the instructions given there to install the server. Once done, come back here and to get started with mongoDB using Node.JS and mongoose package.

Prerequisites:
Mongodb: https://docs.mongodb.com/manual/installation/
Node.JS
mongoose: npm install mongoose

First create a new file called mongo.js and require mongoose.
now let us start with how to connect to the DB. All you need to provide here is a URL and the port and the db to connect to.

For example, mongodb://localhost:27017/example
The port number is optional, if not provided it will default to 27107

Code for connection is as follows:

const mongoose = require('mongoose');
var uri = 'mongodb://localhost/example'
var options = {
    useMongoClient: true,
    reconnectTries: Number.MAX_VALUE, // Never stop trying to reconnect
    reconnectInterval: 500, // Reconnect every 500ms
  };
  function dbConnect(callback) {
    mongoose.connect(uri, options, callback);
    var db = mongoose.connection;
    db.on('error', console.error.bind(console, 'connection error:'));
    db.once('open', function callback () {
    });
  }
  dbConnect(function(err, response) {
    if (!err) {
        console.log("Connection Opened");
    }
  });

When you execute with node mongo.js, you should see “Connection Opened” log on your terminal

Let us now see what has actually happened in the DB
Open the mongo shell by typing in mongo in your terminal. Follow the steps shown below:

vinod@vinod-home-1:~/projects/whatthetech/mongoose$ mongo
MongoDB shell version: 3.2.17
connecting to: test
Server has startup warnings: 
2017-10-23T17:15:14.746+0530 I CONTROL  [initandlisten] 
2017-10-23T17:15:14.746+0530 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2017-10-23T17:15:14.746+0530 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2017-10-23T17:15:14.746+0530 I CONTROL  [initandlisten] 
2017-10-23T17:15:14.746+0530 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
2017-10-23T17:15:14.746+0530 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2017-10-23T17:15:14.746+0530 I CONTROL  [initandlisten] 
> show dbs
local  0.000GB
test   0.000GB
> 

As you can see, there is no db called “example”
The reason is, we have not really defined any schema and everything right now is in memory. Until we call save the we will not see anything as the databases are empty

Let us now create a schema. Since we will be using this blog as the base for all future mongo blogs, we will keep our file structure clean. Create another file called dao.js
For the remainder of this blog, we will create a schema using youtube data and we will use youtube’s actual data to populate the DB and perform other operations.
Sample Youtube Data: youtube
Let us now create our schema using the fields available in youtube.txt

in dao.js, add the below lines:

const mongoose = require('mongoose');
//Creating schema
var youtubeSchema=new mongoose.Schema({
    _id:String,
    channelId:{type: String, default: ''},
    title:{type: String, default: ''},
    description: {type: String, default: ''},
    defaultLanguage: {type: String, default: ''},
    categoryId: {type: Number, default: 0},
    duration: {type: Number, default: 0},
    viewCount: {type: Number, default: 0},
    likeCount: {type: Number, default: 0},
    dislikeCount: {type: Number, default: 0},
    favoriteCount: {type: Number, default: 0},
    commentCount: {type: Number, default: 0},
});
mongoose.model('Youtube',youtubeSchema);
var Youtube=mongoose.model('Youtube');

To make things easy for this and all future blogs, let us create a small service. Create a new file called server.js and add the below code to it.

var express = require('express');
var db = require('./mongo');
const dao = require('./dao');
var app; 
db.dbConnect(function(err, response) {
    if (!err) {
        console.log("Connection Opened");
        app = express();
        
        app.listen(3000);
        app.post('/updateSchema', function(req, res) {
            dao.updateSchema().then(response=>{
                console.log('/updateSchema');
                res.status(200).send('Updated schema');
            })
            .catch(err=>{
                console.log(err);
                res.status(400).send('Failed to update schema');
            });
        });
    }
});

As you can see, we are using express, so, install express : “npm install express”
In dao.js, add the following lines of code to insert one dummy document.

mongoose.model('Youtube',youtubeSchema);
var Youtube=mongoose.model('Youtube');
module.exports = {
    updateSchema: function (videoObj) {
        return new Promise(function(resolve, reject) {
            Youtube.insertMany(videoObj, function (err, response) {
                if (err) {
                    return reject(err);
                }
                return resolve();
            });
        });
    }
}

We now have everything ready. All we need to do now is call our /updateSchema api. We can do this using postman (https://www.getpostman.com/)
Copy the contents of youtubeschema to the body of postman after selecting “raw” and “JSON” and then press “Send”
The data would now be inserted into DB. You can verify that using mongo-shell by following the below steps:

> show dbs
example  0.000GB
local    0.000GB
test     0.000GB
> select example
2017-10-24T21:10:05.503+0530 E QUERY    [thread1] SyntaxError: missing ; before statement @(shell):1:7
> show collections
youtubes
> db.youtubes.find()
{ "_id" : ObjectId("59ef5cfb4b821c30d7c63bde"), "__v" : 0, "commentCount" : 0, "favoriteCount" : 0, "dislikeCount" : 0, "likeCount" : 0, "viewCount" : 0, "duration" : 0, "categoryId" : 0, "defaultLanguage" : "", "description" : "", "title" : "", "channelId" : "" }
> 

You can see that all the fields have been populated with default values that we had specified and since we did not specify any id, mongo auto generated the _id

This concludes our post on Connecting to Mongo and verifying that the connection is successful by creating a schema and inserting an empty document.

Tags: , , ,