Zero to Hero – Node.js (part -4) – DB Connection
8 mins read

Zero to Hero – Node.js (part -4) – DB Connection

In previous article, we learn about using Express JS framework in Node.js. Today, we will learn about connecting Node.js application with MongoDB.

We will talk about the MongoDB ODM library mongoose and learn how to connect node.js with the MongoDB using the Mongoose ODM library.

Before diving into this, let’s go through some basic terminology

MongoDB

MongoDB is a database that stores your data as documents. Most commonly these documents resemble a JSON-like structure :

{
firstName: "Akash",
lastName: "Rajput"
}

Then we create a document and place it within a collection. For example, we could create a document as user and this user document can be part of users collection. Best thing in MongoDB is that this user object doesn’t require above 2 attributes

One of the key factors with MongoDB is its flexibility when it comes to structure. Even though in the first example, the user object contained a firstName and lastName property, these properties are not required in every user document that is part of the users collection. This is what makes MongoDB very different from a SQL database like MySQL or Microsoft SQL Server that requires a strongly-defined database schema of each object it stores.

So, Before anything else, let’s install MongoDB in our system. For this demo purpose, I’m going to use MongoDB Community Edition, but you can also work with Enterprise one. For installation, please go through this link.

Mongoose

Mongoose is an Object Document Mapper (ODM). It allows one to define objects with a strongly-typed schema that is mapped to a MongoDB document.

Below are eight SchemaTypes in Mongoose

  • String
  • Number
  • Date
  • Buffer
  • Boolean
  • Mixed
  • ObjectId
  • Array

Set-up Mongoose

First, we need to create a new project in Node.js using npm init. I’m leaving it up to you for project creation, but let’s use app starting point as “server.js” only.

Execute below command in terminal after your project creation:

npm install mongoose --save

Now, create server.js file in project root directory with below code:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mongoose_basics')
view raw server.js hosted with ❤ by GitHub

So, 1st line is to include mongoose library and 2nd is to open connection to DB mongoose_basics.

Let’s first understand about connect function. It can one mandatory parameter and two optional parameters. Syntax for connect function is like this:

mongoose.connect(uri /* mandatory */, options /* optional */, function(error) /* optional */ {
 
// Check error in initial connection. There is no 2nd param to the callback.
 
});

Now, let’s update our server.js code with function callback to handle errors like below:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mongoose_basics', function (err) {
if (err) throw err;
console.log('Successfully connected');
});
view raw server.js hosted with ❤ by GitHub

Try running it from console and verify the connection. If you see Successfully connected , then it’s all right. You did a good job.

Note: If you see any warning about depreciation of methods, then update the code like below:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mongoose_basics', {useNewUrlParser: true, useUnifiedTopology: true} , function (err) {
if (err) throw err;
console.log('Successfully connected');
});
view raw server.js hosted with ❤ by GitHub

Mongoose is now set up and connected to a database called mongoose_basics. My connection is using no username, password, or custom port. If you want to set these options then please review Mongoose Documentation on connecting. The documentation provides detailed explanations.

Let’s move to next step……

Mongoose Schema

Mongoose schema can be created using Schema. Let’s use our old friend User schema like this:

let userSchema = mongoose.Schema({
    firstName: String,
    lastName: String
});

Let’s expand upon this example by converting the first and last name properties to be child objects of name property:

let userSchema = mongoose.Schema({
name: {
firstName: String,
lastName: String
},
created: Date
});

Once schema is created then we can create our Model like this:

let User = mongoose.model('User', userSchema);

Once schema is created then we need to export the schema.

Create a new folder models in root directory and create a new file users.js with below code:

let mongoose = require('mongoose');
let userSchema = mongoose.Schema({
name: String,
email: String
});
let User = mongoose.model('User', userSchema);
module.exports = User;
view raw users.js hosted with ❤ by GitHub

Now, let’s update our server.js file with below code:

var mongoose = require('mongoose');
var User = require('./models/user')
mongoose.connect('mongodb://localhost/mongoose_basics', { useNewUrlParser: true, useUnifiedTopology: true }, function (err) {
if (err) throw err;
console.log('Successfully connected');
let newUser = User({
name: 'demo',
email: 'demo@demo.com'
});
// save the user
newUser.save(function (err) {
if (err) throw err;
console.log('User created successfully.');
});
});
view raw create_user.js hosted with ❤ by GitHub

Above code will be create a user named demo in MongoDB. run the server.js file and verify it.

Below is the updated server.js file in which I’ve written some more logic like reading from DB and Deleting db value. Probably there are more out there and you can learn it from mongoose site.

var mongoose = require('mongoose');
var User = require('./models/user')
mongoose.connect('mongodb://localhost/mongoose_basics', { useNewUrlParser: true, useUnifiedTopology: true }, function (err) {
if (err) throw err;
console.log('Successfully connected');
let newUser = User({
name: 'demo',
email: 'demo@demo.com'
});
// save the user
newUser.save(function (err) {
if (err) throw err;
console.log('User created successfully.');
});
//Read All user data
User.find({}, function (err, users) {
if (err) throw err;
// object of all the users
console.log(users);
});
// get the user data with email demo@demo.com
User.find({ email: 'demo@demo.com' }, function (err, user) {
if (err) throw err;
// object of the user
console.log(user);
});
// find the user with email demo@demo.com
User.findOneAndRemove(
{ email: 'demo@demo.com' },
function(err) {
if (err) throw err;
// we have deleted the user
console.log('User deleted successfully.');
});
});
view raw server.js hosted with ❤ by GitHub

That’s for this blog. In next part, we will learn about exposing these DB as API via node.js.

Till then….


Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.