Working with database in Express App

Share

Read Previous: Controllers & Middleware

Now, in the series of node js backend development, it is time to work with databases. We use the database in our application to store data.

Generally, we use MongoDB or MySQL with the express app as our database.

MongoDB

Installing MongoDB in your system

Go to the MongoDB website and download the MongoDB compass and install it. While installing compass make sure you check for the MongoDB server option. After installing, start it for the first time and it will be running forever on port 27017 until you stop it.

Now, in your express, install mongoose package which provides drivers and a gateway to connect the database with your application.

npm install mongoose

installing mongoose

Creating Connection

After this step, we write some code to connect the database. At first, we import the mongoose package and store it in a constant value. Then, we call a function connect() to create a connection.

To connect MongoDB, we need a connection string, which looks like this:

const mongodb_url = mongodb://localhost:27017/database_name?options

Here is a basic code snippet

const express = require('express')
const app = express()
const mongodb = require('mongoose')

const mongodb_url = `mongodb://localhost:27017/backendapp?retryWrites=true&w=majority`

mongodb.connect(mongodb_url).then(()=>console.log("+ Database Connected!!"))
.catch(error=>console.log(error))

app.listen(3000, () => {
  console.log(`+ Express App Started\n+ Port:${3000}`)
})

When you start your node application it will log a message in the terminal.

Tips: To keep your app running and auto-reload after any changes in files, use nodemon.

Cheers!! we have successfully created a connection with the MongoDB server. In the next article, we will talk more about data models and rules.

MySQL

Connecting MySQL

To connect to MySQL, you need to install the MySQL server on your PC first. if you have installed it already, let’s see how to connect MySQL server.

we need to install mysql package for node js. To do it, run the command : npm install mysql in your project folder.

To create a connection, we need to construct a configuration object for the MySQL connection. it looks like this:

const config = { 
      host: 'localhost', // host for connection 
      port: 3307, // default port for mysql is 3306 
      database: 'backendapp', // database from which we want to connect
      user: 'root', // username of the mysql connection 
      password: '' // password of the mysql connection 
    }

Second, we have a function mysql.createConnection(config) this returns an instance of the MySQL server. Then, we have a connect(callback) function to create a connection.

const connection = mysql.createConnection(config)
connection.connect(error=>{
  if(error){
    console.log("- Failed to connect MySQL server")
  }else{
    console.log("+ MySQL Server connected");
  }
})

The complete code:

const express = require('express')
const app = express()
const mysql = require('mysql')

const config = { 
      host: 'localhost', 
      port: 3307,
      database: 'backendapp', 
      user: 'root', 
      password: '' 
    }

const connection = mysql.createConnection(config)
connection.connect(error=>{
  if(error){
    console.log("- Failed to connect MySQL server")
  }else{
    console.log("+ MySQL Server connected");
  }
})

app.listen(3000, () => {
  console.log(`+ Express App Started\n+ Port:${3000}`)
})

In this series of backend application development, we will use MongoDB as our database. This article is all about creating a database connection using different databases. see you at the next one.

If you are facing any problem with connecting a database, feel free to reach out to me at our Instagram handle.

Share
Sudeep Mishra

Sudeep Mishra

Healing

Leave a Reply

Your email address will not be published.

%d bloggers like this: