45-Nodejs Course 2023: Database Models: Default Values
Tags: node, typescript, mongodb, fastify
Published: 2022-11-07 04:52:33

---
title: 45-Nodejs Course 2023: Database Models: Default Values
published: true
description: 
series: Nodejs Course 2023
tags: nodejs, typescript, mongodb, fastify
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kzgn0vdu9ccm0yi1qibs.png
# Use a ratio of 100:42 for best results.
---

Let's move to another important section, which is the default value for the model, in that sense, we want to set initial values for the model, for example, we want to set the `published` column to be `false` if the column itself does not exist.

However, this should only be done in the `create` operation, not in the `update` operation as we might later want to remove that column from that certain document.

Now let's go and add it.

```ts
// src/core/database/model/model.ts
import { Document, ModelDocument } from "./types";

export default abstract class Model extends CrudModel {
  // ...
  /**
   * Define Default value data that will be merged with the models' data
   * on the create process
   */
  public defaultValue: Document = {};
}
```

We defined an empty object here which will be used to store the default values for the model.

Now let's update the `save` method to apply the default values.

```ts
// src/core/database/model/model.ts
import { Document, ModelDocument } from "./types";
import Is from "@mongez/supportive-is";import {
  areEqual,
  except,
  get,
  merge,
  only,
  set,
} from "@mongez/reinforcements";

export default abstract class Model extends CrudModel {
  // ...
  
  /**
   * Perform saving operation either by updating or creating a new record in database
   */
  public async save(mergedData: Document = {}) {
    this.merge(mergedData);

    // check if the data contains the primary id column
    if (this.data._id && !this.isRestored) {
      // perform an update operation
      // check if the data has changed
      // if not changed, then do not do anything
      if (areEqual(this.originalData, this.data)) return;

      this.data.updatedAt = new Date();

      await queryBuilder.update(
        this.getCollectionName(),
        {
          _id: this.data._id,
        },
        this.data,
      );
    } else {
      // creating a new document in the database
      const generateNextId =
        this.getStaticProperty("generateNextId").bind(Model);

      // check for default values and merge it with the data
      this.checkDefaultValues();

      // if the column does not exist, then create it
      if (!this.data.id) {
        this.data.id = await generateNextId();
      }

      const now = new Date();

      // if the column does not exist, then create it
      if (!this.data.createdAt) {
        this.data.createdAt = now;
      }

      // if the column does not exist, then create it
      if (!this.data.updatedAt) {
        this.data.updatedAt = now;
      }

      this.data = await queryBuilder.create(
        this.getCollectionName(),
        this.data,
      );
    }
  }
  
  /**
   * Check for default values
   */
  protected checkDefaultValues() {
    // if default value is empty, then do nothing
    if (Is.empty(this.defaultValue)) return;

    // merge the data with default value
    this.data = merge(this.defaultValue, this.data);
  }
}
```

We added in the create process a new method called `checkDefaultValues` which will be called before the data is saved to the database.

In this method, we checked if the default value property is empty, if it is, then we do nothing, otherwise, we merge the default value with the data.

The [merge](https://github.com/hassanzohdy/reinforcements#merging-objects-deeply) will merge data deeply, so if the data already has a column, then it will not be overridden.

Now let's give it a try!

```ts
// src/app/users/models/user.ts

import { Model } from "core/database";
import { Document } from "core/database/model/types";

export default class User extends Model {
  /**
   * Collection name
   */
  public static collectionName = "users";

  /**
   * {@inheritDoc}
   */
  public defaultValue: Document = {
    published: true,
  };
}
```

We added `published` column to be true by default.

Now let's create a new user and see what happens.

```ts
// src/app/users/routes.ts
import User from './models/user';

const user = await User.create({
  name: 'hasan',
});

console.log(user.data); // {id: 1, name: 'hasan', published: true, _id: '...', createdAt: '...', updatedAt: '...'}
```

We'll see something like this:

![Success user](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ndxaqoqoa64kq7dxln1a.png)

And that's it!

## 🎨 Conclusion

In this section, we learned how to set default values for the model, and we also learned how to use the `merge` method to merge data deeply.

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