30-Nodejs Course 2023: Database Models: Introduction
Tags: node, typescript, mongodb, fastify
Published: 2022-11-03 07:20:39

---
title: 30-Nodejs Course 2023: Database Models: Introduction
published: true
description: 
series: Nodejs Course 2023
tags: nodejs, typescript, mongodb, fastify
#cover_image: 
# Use a ratio of 100:42 for best results.
---

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:

```bash
# App Configurations
PORT=3000
BASE_URL=localhost
DEBUG=true
APP_NAME="My App"

# Database Configurations
DB_HOST=localhost
DB_PORT=27017
DB_NAME=root
DB_USERNAME=root
DB_PASSWORD=ninjaNode
```

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

```ts
// 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;
```

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](https://www.mongodb.com/docs/manual/reference/method/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](https://github.com/hassanzohdy/nodejs-2023)

## 😍 Join our community

Join our community on [Discord](https://discord.gg/pb2vmdfhGf) 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](https://www.youtube.com/playlist?list=PLGO8ntvxgiZMJc7RN2lIq9WmMOlWZGzmz), 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

- [Event Driven Architecture: A Practical Guide in Javascript](https://dev.to/hassanzohdy/event-driven-architecture-the-best-paradigm-that-i-love-to-work-with-in-javascript-and-node-js-1gnk)
- [Best Practices For Case Styles: Camel, Pascal, Snake, and Kebab Case In Node And Javascript](https://dev.to/hassanzohdy/best-practices-for-case-styles-camel-pascal-snake-and-kebab-case-in-node-and-javascript-55oi)
- [After 6 years of practicing MongoDB, Here are my thoughts on MongoDB vs MySQL
](https://dev.to/hassanzohdy/after-6-years-of-practicing-mongodb-here-are-my-thoughts-on-mongodb-vs-mysql-574b)

Packages & Libraries

- [Collections: Your ultimate Javascript Arrays Manager](https://dev.to/hassanzohdy/collections-your-ultimate-javascript-array-handler-3o15)
- [Supportive Is: an elegant utility to check types of values in JavaScript](https://dev.to/hassanzohdy/supportive-is-an-elegant-utility-to-check-types-of-values-in-javascript-1b3e)
- [Localization: An agnostic i18n package to manage localization in your project](https://dev.to/hassanzohdy/mongez-localization-the-simplest-way-to-translate-your-website-regardless-your-favorite-framework-4gi3)

 React Js Packages

- [useFetcher: easiest way to fetch data in React Js](https://dev.to/hassanzohdy/usefetcher-the-easiest-way-to-fetch-data-in-react-45o9)

Courses (Articles)

- [React Js: Let"s Create File Manager With React Js and Node Js](https://dev.to/hassanzohdy/lets-create-a-file-manager-from-scratch-with-react-and-typescript-chapter-i-a-good-way-to-expand-your-experience-5g4k)