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;
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",
};
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;
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;
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;
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
- Event Driven Architecture: A Practical Guide in Javascript
- Best Practices For Case Styles: Camel, Pascal, Snake, and Kebab Case In Node And Javascript
- After 6 years of practicing MongoDB, Here are my thoughts on MongoDB vs MySQL
Packages & Libraries
- Collections: Your ultimate Javascript Arrays Manager
- Supportive Is: an elegant utility to check types of values in JavaScript
- Localization: An agnostic i18n package to manage localization in your project
React Js Packages
Courses (Articles)
Top comments (0)