17-Nodejs Course 2023: Creating New Database
Tags: node, typescript, mongodb, fastify
Published: 2022-10-31 12:41:50

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

So far so good, now let's go ahead and directly connect to a database.

## Connecting to Database

In MongoDB, its that easy that you can connect to the database by just passing the name, if the database does not exist, it will create it for you!

```ts
// src/core/database/connection.ts
import config from "@mongez/config";
import chalk from "chalk";
import { MongoClient } from "mongodb";

export class Connection {
  /**
   * Mongo Client
   */
  public client?: MongoClient;

  /**
   * Connect to the database
   */
  public async connect() {
    const host = config.get("database.host", "localhost");
    const port = config.get("database.port", 27017);
    const username = config.get("database.username", "");
    const password = config.get("database.password", "");
    // 👇🏻 Add the database name
    const databaseName = config.get("database.name");

    try {
      this.client = await MongoClient.connect(`mongodb://${host}:${port}`, {
        auth: {
          username: username,
          password: password,
        },
      });
      
      // 👇🏻 Now let's connect to the database
      const database = await this.client.db(databaseName);

      console.log(
        chalk.green("Connected!"),
        !username || !password
          ? chalk.red("Your not making a secure authenticated connection!")
          : "",
      );

    } catch (error) {
      console.log(error);
    }
  }
}

const connection = new Connection();

export default connection;
```

So what we did is we just called `client.db` method and passed the database name, now let's update the database configuration file and add `name` key to it.

```ts
// src/config/database.ts
export const databaseConfigurations = {
  host: "localhost",
  port: 27017,
  username: "root",
  password: "root",
  name: "ninjaNode",
};
```

Now the database is connected, but so far we can not access it, so let's create a property that will hold the database instance.

```ts
// src/core/database/connection.ts
import config from "@mongez/config";
import chalk from "chalk";
import { Db, MongoClient } from "mongodb";

export class Connection {
  /**
   * Mongo Client
   */
  public client?: MongoClient;

  /**
   * Database instance
   */
  public database?: Db;

  /**
   * Connect to the database
   */
  public async connect() {
    const host = config.get("database.host", "localhost");
    const port = config.get("database.port", 27017);
    const username = config.get("database.username", "");
    const password = config.get("database.password", "");
    const databaseName = config.get("database.name");

    try {
      this.client = await MongoClient.connect(`mongodb://${host}:${port}`, {
        auth: {
          username: username,
          password: password,
        },
      });

      this.database = await this.client.db(databaseName);

      console.log(
        chalk.green("Connected!"),
        !username || !password
          ? chalk.red("Your not making a secure authenticated connection!")
          : "",
      );
    } catch (error) {
      console.log(error);
    }
  }
}

const connection = new Connection();

export default connection;
```

From this point now we can access the database instance of mongodb through `connection.database` property, but let's make it more fancy.

## Database Service

Let's create a service that will hold the database instance, so we can access it from anywhere in the application.

```ts
// src/core/database/database.ts
import { Db } from "mongodb";

export class Database {
  /**
   * Database instance
   * 
   * 👇🏻 The `!` will tell typescript don't worry this property will have a value, just don't throw any bloody errors -_-
   */
  public database!: Db;

  /**
   * Set the database instance
   */
  public setDatabase(database: Db) {
    this.database = database;

    return this;
  }
}

const database = new Database();

export default database;
```

We created a database class that will receive the database handler of Mongodb, and it will be stored directly to public property we called it `db`.

Now let's update our connection class to return the database instance.

```ts
// src/core/database/connection.ts
import config from "@mongez/config";
import chalk from "chalk";
import { MongoClient } from "mongodb";
// 👇🏻 Import the database instance and its type
import database, { Database } from "./database";

export class Connection {
  /**
   * Mongo Client
   */
  public client?: MongoClient;

  /**
   * Database instance
   */
  public database?: Database;

  /**
   * Connect to the database
   */
  public async connect() {
    const host = config.get("database.host", "localhost");
    const port = config.get("database.port", 27017);
    const username = config.get("database.username", "");
    const password = config.get("database.password", "");
    const databaseName = config.get("database.name");

    try {
      this.client = await MongoClient.connect(`mongodb://${host}:${port}`, {
        auth: {
          username: username,
          password: password,
        },
      });

      // get the database
      const mongoDBDatabase = await this.client.db(databaseName);

      // create the database instance
      this.database = database.setDatabase(mongoDBDatabase);

      console.log(
        chalk.green("Connected!"),
        !username || !password
          ? chalk.red("Your not making a secure authenticated connection!")
          : "",
      );
    } catch (error) {
      console.log(error);
    }
  }
}

const connection = new Connection();

export default connection;
```

A question here, why we did create an instance of `Database` and exported it as default? well because now you can easily use it from anywhere in your project.

## Conclusion

In this article we learned how to connect to mongodb database using typescript, and how to create a database service that will hold the database instance, so we can access it from anywhere in the application.

In our next article we'll make a break and refactor our code a little bit to be more cleaner as we're growing bigger.

## 🎨 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/vtZE9YzaFz) 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)