19-Nodejs Course 2023: Database Collections
Tags: node, typescript, mongodb, fastify
Published: 2022-10-31 17:52:02

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

If you are struggling in any step of this course, please feel free to ask me in the comments section below or join our [discord channel](https://discord.gg/pb2vmdfhGf).

## Database Collections

As we mentioned earlier, the data are stored in collections which is referred as well to `Tables`, now we want to know how to create or get a collection using Nodejs, it's just as easy as you may think, just call the `collection` method from the database :)

## Users Collection

Open `src/app/users/controllers/list-users.ts` and update it to the following code

```ts
// src/app/users/controllers/list-users.ts
import database from "core/database";

export default async function usersList(request: any) {
  const usersCollection = database.database.collection("users");

  const usersList = await usersCollection.find({}).toArray();

  return {
    users: usersList,
  };
}
```

> Don't forget to async the function

What we did here we called our `database` class which internally holds the `mongodb database driver`, then we called `collection` method and passed to it our collection name which we'll call `users`.

Now we have an instance of collection, we can use it to perform operations on it, in this case we called `find` method which returns a cursor, then we called `toArray` method which returns an array of documents.

You should see now an empty array in the response, because we don't have any users in our database, let's add some users.

## Enhancing the collection call

Calling `database.database` is not a good practice, so let's make it better, open `src/core/database/database.ts` and update it to the following code

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

export class Database {
  /**
   * Database instance
   */
  public database!: Db;

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

    return this;
  }

  /**
   * Get database collection
   */
  public collection(collectionName: string) {
    return this.database.collection(collectionName);
  }
}

const database = new Database();

export default database;
```

Now we can use the `collection` method directly from the `database` instance, open `src/app/users/controllers/list-users.ts` and update it to the following code

```ts
// src/app/users/controllers/list-users.ts

export default async function usersList(request: any) {
  const usersCollection = database.collection("users");

  const usersList = await usersCollection.find({}).toArray();

  return {
    users: usersList,
  };
}
```

## Create New User

Now we want to create a new user, open `src/app/users/controllers/create-user.ts` and update it to the following code

```ts
// src/app/users/controllers/create-user.ts
import database from "core/database";

export default async function createUser(request: any) {
  // we'll use this for now because of the multiple part, but we'll fix it later
  const name = request.body.name.value;
  const email = request.body.email.value;

  const users = database.collection("users");

  const result = await users.insertOne({
    name,
    email,
  });

  return {
    user: {
      id: result.insertedId,
      name,
      email,
    },
  };
}
```

> Don't forget to async the function

Now let's open postman and create a new user by just adding the following body

```json
{
  "name": "Hasan",
  "email": "hassanzohdy@gmail.com"
}
```

And that's it! you should see now the same email and name with the a generated id.

## Conclusion

In this lesson we learned how to create a collection and how to use it to perform operations on it, we also learned how to create a new user and how to get all users.

## Next Lesson

In the next lesson we'll start working with Database `Models`!

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