blog d.png

Start and The Ultimate Guide to Connect Your Node JS Application With MongoDB SQL

Mongoose is an “Object Document Mapper (ODM)”, while Sequelize is an "Object Relational Mapper (ORM), both of the modules simplify DB low layer operations by mapping the objects. Sequelize is used with relational databases while mongoose is particularly used with MongoDB. Before continuing with this article you will need to have hands-on Express & Node.js.

Summary

  • Introduction Mongoose & Sequelize
  • Getting Started with Mongoose.js
  • Prerequisites
  • Installing Mongoose on a Node.js environment
  • ○ Creating the connection
  • Create the schema & Model
  • Create Your First Entry
  • Get Users

Sequelize ORM

  • Prerequisites
  • SQL
  • ORM
  • Using Sequelize
  • Benefits Of Using Sequelize

Not only does node js allow you to communicate with MySQL or other SQL databases but also supports NoSQL databases. Mongoose And Sequelize connect your Node.js app with the database. While Mongoose is used to connect NodeJS applications with MongoDB and on the other hand Sequelize helps to connect with PostgreSQL, MySQL, and Microsoft SQL Server databases. “Mongoose provides a straightforward, schema-based solution to model your application data. It includes built-in type casting, validation, query building, business logic hooks, and more, out of the box.” - https://mongoosejs.com/ “Sequelize is a promise-based ORM for Node.js and io.js. It supports the dialects PostgreSQL, MySQL, MariaDB, SQLite, and MSSQL and features solid transaction support, relations, read replication, and more.” - https://sequelize.org/v3/ The agenda for this article is to provide you with a way to get started with both the libraries and get your Node application run with the database.

Getting Started With Mongoose.js

Getting Started With Mongoose.js MongoDB is the most simple yet popular No-SQL database among developers. It uses JSON-like documents with optional schemas, which makes it the best choice for JS developers. Mongoose.js is a library that reduces the boilerplate to connect your Node Application to MongoDB.


Prerequisites

  • Node JS downloaded & installed on your machine.
  • Node JS basic concepts. Refer to The Node JS docs
  • Express JS basic concepts. Refer Express docs
  • MongoDB Compass running on your machine. You can also use atlas which is a remote instance of MongoDB.

Installing Mongoose on a Node.js environment

init your Node JS backend project and install the required dependencies.

$ npm init —-yes


We will be requiring express to create the HTTP server, we won't be using HTTP module by node as it will be another boilerplate. Also, we will be using mongoose to connect our node application with DB

$ npm install express mongoose --save


Creating the connection

Create a file server.js , import all the required dependencies and call mongoose.connect(uri , options , callback) Server.js


const mongoose = require("mongoose"); mongoose.connect("mongodb://localhost/test",
{ useNewUrlParser: true,
useFindAndModify: false,
useUnifiedTopology: true
}, () => {
console.log("connected");
});


Make sure your mongo is running on localhost on the default port. For atlas your URI will be:

`mongodb+srv://${usrname}:${pass}@${cluster}.mongodb.net/${db_name}?retryWrites=true&w=majority`,


To make sure your connection was successful, add the following code right below your mongoose.connect(). Now at last app.listen() on 3000 port with a success callback.

app.listen(3000, () => { console.log("Server is running"); });


Create the schema & Model

According to Node JS, best practices use a different folder for all your views, models, routes. Create file user.js and add the following code. user.js

const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema({
name: String,
age: Number,
});
const User = mongoose.model("User", UserSchema);
module.exports = User;


Create Your First Entry

// import user model
// use this code on any post route
const user = new User(request.body); // json body parser
try {
await user.save(); // user.save() is an async call
response.send(user);
} catch (error) {
response.status(500).json({“msg”:”something went wrong”});
}


Get Users

Add the following lines of code to the routes.js file. routes.js

// import user model
app.get("/getUsers", async (req, res) => {
const users = await user.find({}); // finds all user
try {
res.json(users);
} catch (err) {
res.status(500).json(“msg”:err.message);
}
});

That's pretty much it now you have successfully created your first entry in MongoDB and fetched it successfully. To dive more into it please visit this documentation https://mongoosejs.com/docs/guide.html

Sequelize ORM


Prerequisites

We will be using sequelize library to connect our node application with our SQL database:

npm install sequelize


SQL

Structured Query Language (SQL) is a programming language that allows us to manage relational databases by performing queries.

Object Relational Mappers (ORM)

Object Relational Mapping is a way to map data in objects directly into the database without performing any query. Sequelize supports PostgreSQL, MySQL, MariaDB, SQLite, and Microsoft SQL Server databases. Sequelize is an open-source library that enables developers to work with relational databases more easily.


Using Sequelize

First create a Node JS project with sequelize.

const Sequelize = require('sequelize');
const con = new Sequelize("db_name", "username", "password" ,  {
      dialect: 'mysql',  
        // By default host is 'localhost'           
        host: 'localhost'
    }
);
const Borrower = connection.define("borrower", {
  Name: Sequelize.String,
  Book: Sequelize.String
});
con.sync();
// query using sequelize API
Borrower.findById(2).then(function (val) {
  console.log(val);
})


Benefits of Sequelize

  • Less boilerplate.
  • Zero SQL queries.
  • Abstract database engine.
  • Flexible and easy migrations.

Conclusion

Using No-SQL or SQL databases is completely your choice. It depends on the application and uses cases. I hope by the end of this article how you can save your time in database maintenance with the help of these cool libraries. At last to run a node js project use :)))))) npm run start console.log(“Happy Coding”);

Leave a comment