Object Relational Mapping & Object Data Mapper – Node.js Approaches

621 VIEWS

·

Object Relational Mapping (ORM) is a simplified way of converting data between the relational database and objects. Object NoSql Data Mappers (ONDM), also known as Object Data Mappers (ODM), serve the same purpose of mapping data objects into a database structure, particularly for NoSQL databases. In this tutorial, we will look at Node.js implementation approaches for ORMs and ODNMs.

Why ORMs and ODMs?

As a developer, you may have encountered an instance where you have to write complex SQL statements to manipulate/retrieve data from a database. Worse, at times, you still need to convert the database records/data into an object that is compatible with your preferred programming language. For instance, in Java, you will need to instantiate an object around the data to process the SQL records. Below is a snippet describing this use case:

//write SQL to retrieve hospitals

sql_stmt = "SELECT * FROM hospital WHERE num_capacity > 20";

sql_result = database.query(sql_stmt);




//Convert the database records into a Java compatible object

all_hospitals = new ArrayList();

for (data : sql_result){

 Hospital hosp = new Hospital();

 hosp.setName(data["name]); 

 hosp.setCapacity(data["capacity");

 all_hospitals.add(hosp)

}

As shown above, we have to mechanically convert the SQL results into an object that is compatible with the programming language of your choice; in this case, Java.

Here’s where things get simplified and elegant with ORMs. Object Relational Mappers have the capability of writing query statements in object-oriented programming language instead of writing SQL or NoSQL statements through high-level abstraction. Stated differently, ORMs provide object methods to enable developers to interact with the underlying database engines. So we could have achieved the above task by using the ORM implementation below, without any manual data conversion:

all_hospitals = Hospital_ORM_Table.query(capacity > 20)

The use of ORMs or ODMs additionally simplifies the process of changing the database engine whenever the need arises. 

 A Closer Look at How ORMs and ODMs Work

  • The first step involves deciding on the type of database you want to use. Once you decide on the type and name of the database that will support your application, look for the Object Relational Mapping or Object Data Mapper that works perfectly with the choice of your database and install it. If you’re using Node.js, for instance, you would consider sequelize.
npm install sequelize
  • The second step involves building a database model. A database model represents the logical structure of a database, whether an SQL or NoSQL database. A database model typically takes a form of a class object that contains the data structure and constraints of the database. One added benefit of using a database model is that it provides many benefits such as efficiency and scalability. The structure of the database defined in the model includes database collection, documents (for No-SQL databases) or tables, columns if it is a relational database. 
  • The third step is writing code that connects to the database. 

Types of ORMs

As the name suggests, Object Relational Mapping are designed for relational databases. Below are some of the known ORMs that support Nodejs:

  • Node-ORM, Bookshelf, Objection.js. These types of ORMs work perfectly with MySQL, SQLite, and PostgreSQL databases.
  • Caminte is a powerful ORM that supports a large number of database formats such as MySQL Sqlite3, Riak, Postgres, Couchdb, Mongodb, Redis, Neo4j, Firebird, Rethinkdb, Tingodb. 
  • Sequelize  ORM fully supports PostgreSQL, MySQL, MariaDB, SQLite, and Microsoft SQL Server database formats. 

Types of ODMs

Multiple ODMs are designed to support different NoSQL databases. Let’s take a look at the few examples of ODNMs listed below: 

  • Typesaurus is an ODM for Firebase database designed for Typescript developers. 
  • Express-Cassandra is also an ODM, designed to work with Node.js for a NoSQL database like Cassandra. 
  • Powerful NoSQL databases such as DynamoDB, have a helper Dynamo data mapper, an ODM that allows structured data to interact with the database easily. 
  • Mongoose is an ODM for MongoDB database. MongoDB is one of the most commonly used NoSQL databases, we will use Mongoose to build a data model for MongoDB in a Nodejs application. 

Mongoose ODM and MongoDB Database Example

Let’s imagine you are a Junior Developer who recently got hired by your country’s Ministry of Health (why not?). One of your responsibilities is to build a Hospital Ward Management System Node.js application for a local hospital. 

Requirements

  1. You must have MongoDB Compass Community on your machine, or you can use the MongoDB cloud. In this tutorial, we will use the Compass Community, which is installed on my computer. 
  2. You are required to have Node.js on your machine.

The folder and files creation

To begin, create a new folder and name it as “hospital”. Create two sub folders inside hospital and name them “ODM” and “ORM” . In the ODM folder, do the following installations:

Installations

npm init -y

Once the package.json folder that contains metadata of the project is created, install the ODM Mongoose, express, node, and nodemon: 

npm install node express mongoose nodemon --save

 The database we will create shall contain two collections: ward and patients.

Database creation

Let’s first create our hospital database. In it, we create a collection called ward using MongoDB Compass Community. 

The Database Connection

Once you successfully create the MongoDB database, create a database configuration file called mongoose.js. The sole purpose of this file is to connect to the database. In the code below, we have to add mongoose first and use its methods to connect to our local database hospital. 

//connecting to the database

const mongoose = require('mongoose')

mongoose.Promise = global.Promise

mongoose.connect('mongodb://127.0.0.1:27017/hospital', 

{useNewUrlParser : true, useFindAndModify: false})

.then(() => console.log("Hospital Database connected!"))

.catch((error) => console.log(error))




module.exports = mongoose

Output

Here is the output showing that we have successfully connected to our database:

Listening on port 3000
Hospital Database connected!

The Model Creation

The next step is to create an object in Node.js that gives us the structure of our database using the Mongoose ODM. In our ward collection, we created two fields: wardName and numberOfBeds. We shall replicate this structure in our ODM. Also, each document carries different data constraints as required. Once you are done defining the structure of your database, export the model to the file; in my case, index.js.

//hospital database model

const mongoose = require('mongoose')

const wardSchema = new mongoose.Schema({

 wardName: {

  type: String,

  trim: true,

  minlength: 3

 },

 numberOfBeds: {

  type: Number,

  trim: true,

  minlength: 3

 }

})

const hospitalWard = mongoose.model('hospitalWard', wardSchema)

module.exports = hospitalWard

From the above snippet, a ward should contain a limited number of beds (3). We will also create a patient model that would define the structure of the patient collection. We want to know the ward assigned to each patient; therefore, we add a document that contains the ward identification number (_wardId) of type object. The _wardId was automatically generated when we created the ward model. This structure is shown below in our patient ODM.

const mongoose = require('mongoose')

//creating the Schema that enforce constraints on our database

const patientSchema = new mongoose.Schema({

 name: {

  type: String,

  trim: true,

  minlength: 3

 },

 age: {

  type: Integer

 },

 _wardId: {

  type: mongoose.Types.ObjectId,

  required: true,

 }

})

const Patient = mongoose.model('Patient', patientSchema)

module.exports = Patient

Once you finish modeling your database, import the file for connecting to the database and the database model files into the index file. 

const express = require('express')

const app = express()

//connecting to database 

const mongoose = require('./database/mongoose')

//database models

const hospitalWard = require('./database/models/')

const Patient = require('./database/models/')




//Interact with the database(create, add,view and delete)

//app.post()

app.listen(3000, () => console.log("Server is connected on port 3000"))

Take away 

Object-relational mapping is for relational databases, and Object Data Mapping is for NoSQL databases. They both serve the same purpose of allowing us to interact with databases using object-oriented programming. There are multiple ORMs and ODMs specifically designed to support Node.js. Lastly, ORMs or ODMs make it easy to migrate from one database to another.


Primrose Katena is a software engineer, entrepreneur and technical writer. She strongly believes entrepreneurship and technology are positively impacting the world. She has worked in the IT industry in Zimbabwe and Entrepreneurship in Ghana. Ms. Katena loves sharing tech knowledge with other developers through writing.


Discussion

Click on a tab to select how you'd like to leave your comment

Leave a Comment

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

%d bloggers like this: