DEV Community

Hasan Zohdy
Hasan Zohdy

Posted on

30-Nodejs Course 2023: Database Models: Introduction

So we went with the dot env files in our previous article, now let's get back again to database where the heavy and fun work begins.

Updating Database Configurations

Before we go there, let's update the database configurations to use the environment variables.

We'll define 5 environment variables in the .env file:

# App Configurations

# Database Configurations
Enter fullscreen mode Exit fullscreen mode

Now let's update the database.ts file to use these environment variables:

// src/config/database.ts
import { env } from 'dotenv';
const databaseConfigurations = {
  host: env('DB_HOST', 'localhost'),
  port: env('DB_PORT', 27017),
  name: env('DB_NAME'),
  username: env('DB_USERNAME'),
  password: env('DB_PASSWORD'),  

export default databaseConfigurations;
Enter fullscreen mode Exit fullscreen mode

Now we're good to go.

Introduction To Database Models

Let's start by defining what is a database model.

A database model is a representation of a database table (collection) in the code. It's a class that defines the structure of the table and the data types of the columns.

It is also used to make operations over the database collection like creating, reading, updating, and deleting records.

Model Structure

The model structure will be started from a simple structure to a more complex one.

It will begin with the collection name, so we need to define a static property called collectionName that will hold the name of the collection.

The model name will be the singular form of the collection name, the collection name will be always in plural and in camelCase form.

So if we have the following collections:

  • Users Collection: the collection name will be users and the model name will be User.
  • Users Groups Collection: the collection name will be usersGroups and the model name will be UsersGroup.

Why would we name the model in single form? Because we will be using the model to manage a single document (record/row), so it will interact as a single entity.

Collection Of Models

The model will have an operation to get multiple documents from the collection, internally we will loop over these documents and create a new instance of the model (entity) for each document.

CRUD Operations

There is a common term in the database world called CRUD, it stands for Create, Read, Update, and Delete.

These are the basic operations that we will be doing over the database which no model will be complete without them.

Custom Operations

We will also add some custom operations to the model, these operations will be specific to the model and will be used to perform some specific tasks such as truncating the collection, getting the count of the documents, etc.

Unique ID And Auto Increment ID

MongoDB by default generates a column called _id that is a unique ID for each document, it's an ObjectId 12-byte value consisting of:

A 4-byte timestamp, representing the ObjectId's creation, measured in seconds since the Unix epoch.

A 5-byte random value generated once per process. This random value is unique to the machine and process.

A 3-byte incrementing counter, initialized to a random value.

But we'll also create another column called id that it will be an auto incremented integer, which means that the first created document will have the value 1 and the second one will have the value 2, and so on.

Later, we'll add some other cool features like defining the initial value of the model ID, and the increment stepper.

This is actually asked by many clients specially in the orders collection where they want to start the order number from a high number and increment it by higher numbers for each newly created order.

Model Relationships

We'll also add some relationships to the model, these relationships will be used to get related documents from other collections.

Types Of Relationships

There are 3 types of relationships:

  • One To One: a document in the collection has a relationship with a single document in another collection.
  • One To Many: a document in the collection has a relationship with multiple documents in another collection.
  • Many To Many: multiple documents in the collection have a relationship with multiple documents in another collection.

These relations are also called associations in the database world.

But what we'll work with actually is the following:

Embedding (Injecting) a document into another document.

For example when we create a new post, we'll add createdBy column in the post, this will contain the data of the user who created the post which will the user document data that will be stored inside ito.

This is called embedding, and it's a very common practice in MongoDB.

The other way is to inject multiple documents into another document, for example when we create a new post, we'll add comments column in the post, this will contain the data of the comments that are related to the post in an array.

Finally, there are case where we just save the document id because of no need to add the rest of the data or the frequent of change is high or it is too large data so we need only the ids, for example when we create a new post, we'll add commentsIds column in the post, this will contain the ids of the comments that are related to the post in an array.

Model Validation

We'll also add some validation to the model, this validation will be used to validate the data before saving it to the database.

Model Hooks (Events)

We'll also add some hooks to the model, these hooks will be used to perform some tasks before and after saving the document to the database.

Model Scopes

We'll also add some scopes to the model, these scopes will be used to get documents from the collection with some predefined conditions.

For example, we can have a scope called active that will get all the active documents from the collection.

🎨 Conclusion

In this article, we learned about the database models, their structure, and the features that we'll add to them.

🎨 Project Repository

You can find the latest updates of this project on Github

😍 Join our community

Join our community on Discord to get help and support (Node Js 2023 Channel).

🎞️ Video Course (Arabic Voice)

If you want to learn this course in video format, you can find it on Youtube, the course is in Arabic language.

💰 Bonus Content 💰

You may have a look at these articles, it will definitely boost your knowledge and productivity.

General Topics

Packages & Libraries

React Js Packages

Courses (Articles)

Top comments (0)