DEV Community

Hasan Zohdy
Hasan Zohdy

Posted on

17-Nodejs Course 2023: Creating New Database

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!

// 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;
Enter fullscreen mode Exit fullscreen mode

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.

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

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.

// 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;
Enter fullscreen mode Exit fullscreen mode

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.

// 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;
Enter fullscreen mode Exit fullscreen mode

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.

// 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;
Enter fullscreen mode Exit fullscreen mode

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

😍 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)

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!