Creating Data Models for NodeJS Apps with Amplication's React Admin UI
Tags: react, database, node, amplication
Published: 2023-02-16 07:41:19

Data modeling is an essential aspect of building NodeJS applications. It is the process of creating a structured and organized representation of the data that will be used in your application. By properly modeling your data, you can ensure that it is organized, efficient, and easy to work with. In this blog post, we will be discussing the importance of data modeling in NodeJS applications and providing an overview of the different techniques and tools that can be used to model data in NodeJS.

## What is Data Modeling?
Data modeling in NodeJS typically involves creating a schema that defines the structure of the data and the relationships between different types of data. This schema is used to create tables or collections in a database, and it is used to validate, store, and retrieve data within the application.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nrcoq558i5r4ezi6y1l2.png)
[Source](https://en.wikipedia.org/wiki/Data_modeling)

There are two main types of data modeling in NodeJS: Relational data modeling and NoSQL data modeling.

Relational data modeling involves creating a schema that defines the structure of the tables, fields, and relationships in a relational database such as MySQL or PostgreSQL. The schema is used to create tables, and it is used to define the relationships between different tables. This is a traditional way of data modeling and widely used in most of the applications.

[NoSQL data modeling](https://phoenixnap.com/kb/nosql-data-modeling), on the other hand, involves creating a schema for a NoSQL database such as MongoDB. NoSQL databases are document-based, and they do not have a fixed schema. Instead, the schema is defined by the structure of the documents. The data model in NoSQL databases is more flexible and allows for more scalability and performance.

In addition to these, there are also [Object-Relational Mapping](https://www.freecodecamp.org/news/what-is-an-orm-the-meaning-of-object-relational-mapping-database-tools/) (ORM) libraries such as Mongoose and Sequelize that can be used to model data in NodeJS. These libraries provide an abstraction layer between the application and the database, and they can be used to define the schema, validate data, and interact with the database.

In summary, data modeling in NodeJS is an essential part of building NodeJS applications. It involves creating a structured and organized representation of the data that will be used in the application, and it is used to ensure that the data is organized, efficient, and easy to work with. Choosing the right technique and tools for data modeling is critical for ensuring data integrity, scalability, and performance of the application.

## Setting Up a New Project with React Admin
Amplication's React Admin UI, built by [Marmelab](https://marmelab.com/react-admin/) is an open source tool that can help developers create data models for their NodeJS apps quickly and easily. It provides a range of features for defining, validating, and querying data, making it easy to create intuitive and maintainable data structures. Therefore, in today’s tutorial we will be using it to create our data model. 
To get started with React Admin, you'll need to install it and any required dependencies. This can be done using npm (the Node Package Manager).
First, create a new directory for your project and navigate to it in your terminal. Then, run the following command to install React Admin:

```
npm install react-admin
```

Next, you'll need to install any required dependencies. These may include packages such as Redux and GraphQL depending on your needs.
Once all of the necessary dependencies have been installed, you can set up a new React Admin project by creating a new file called "App.js" and importing the necessary components from React Admin.
For example:

```
import { Admin, Resource } from 'react-admin';

const App = () => (
    <Admin>
        // Add your resources here
    </Admin>
);

export default App;
```

## Defining Data Models with React Admin
React Admin allows you to define a wide range of data types, including simple types like strings and numbers, as well as more complex types like relationships and nested objects.
To create a new data model with React Admin, you can use the <Resource> component. For example:

```
import { Admin, Resource } from 'react-admin';

const App = () => (
    <Admin>
        <Resource name="users" />
    </Admin>
);

export default App;
```

This will create a new data model called "users", which you can then customize by adding fields and properties. For example:

```
import { Admin, Resource } from 'react-admin';
import { TextField, EmailField } from 'react-admin';

const App = () => (
    <Admin>
        <Resource name="users" list={UserList}>
            <TextField source="id" />
            <TextField source="name" />
            <EmailField source="email" />
        </Resource>
    </Admin>
);

export default App;
```

This will create a data model for users with three fields: "id", "name", and "email".

## Data Validation with React Admin
[Data validation](https://www.safe.com/what-is/data-validation/) is the process of ensuring that data is entered in a consistent and correct format. This is important because it helps to prevent errors and ensure that data is accurate and reliable. In the context of a NodeJS application, data validation is especially important because it can help to prevent security vulnerabilities and improve the overall user experience.

React Admin provides a number of built-in validation functions that can be used to validate data. These functions can be used to ensure that data meets certain criteria, such as being required, being a certain length, or matching a specific pattern.
React Admin includes a number of built-in validation functions that you can use to validate your data. These functions can be imported from the react-admin package and applied to a field using the validate prop.
For example, you can use the required() function to ensure that a particular field is not left blank:

```
import { required } from 'react-admin';

<TextField source="name" validate={required()} />
```

You can also use the minLength() and maxLength() functions to ensure that a field meets a certain length requirement:

```
import { minLength, maxLength } from 'react-admin';

<TextField source="password" validate={[minLength(8), maxLength(64)]} />
```

In addition to the built-in validation functions provided by React Admin, you can also create your own custom validation functions to fit your specific needs. This can be useful if you have requirements for data validation that are not covered by the built-in functions.
To create a custom validation function, you can define a function that takes in a value and returns an error message if the value is invalid, or undefined if the value is valid.
For example, you might want to create a validation function that checks that a particular field contains a valid email address:

```
const validateEmail = (email) => {
    const regex = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
    if (!regex.test(email)) {
        return 'Invalid email address';
    }
    return undefined;
};

<TextField source="email" validate={validateEmail} />
```

You can then use your custom validation function just like any other validation function in React Admin. You can even combine multiple validation functions using the composeValidators() function, which takes in an array of validation functions and returns a single validation function that runs all of the validation functions in sequence.

```
import { composeValidators } from 'react-admin';

<TextField source="password" validate={composeValidators(required(), minLength(8), maxLength(64))} />

```

This will ensure that the "password" field is required, has a minimum length of 8 characters, and has a maximum length of 64 characters.

## Querying Data with React Admin
Once you have defined your [data models](https://amplication.com/#data-models) and set up validation, you'll want to query your data in order to display it or use it in your application. React Admin provides a number of different methods for querying data depending on your needs.

One way to query data is to use React Admin's <List> component. This component allows you to fetch and display a list of records from your data model. For example:

```
import { List } from 'react-admin';
import { TextField } from 'react-admin';

const UserList = (props) => (
    <List {...props}>
        <TextField source="id" />
        <TextField source="name" />
        <TextField source="email" />
    </List>
);
```

This will fetch a list of user records and display their "id", "name", and "email" fields.
Another way to query data is to use React Admin's <ReferenceField> component. This component allows you to create relationships between different data models and display related data. For example:

```
import { ReferenceField } from 'react-admin';
import { TextField } from 'react-admin';

const PostList = (props) => (
    <List {...props}>
        <TextField source="id" />
        <TextField source="title" />
        <ReferenceField label="Author" source="author_id" reference="users">
            <TextField source="name" />
        </ReferenceField>
    </List>
);
```

This will fetch a list of post records and display their "id", "title", and the "name" of the related user (as specified by the "author_id" field).

## Conclusion
In conclusion, data modeling is an essential aspect of building NodeJS applications. It is the process of creating a structured and organized representation of the data that will be used in your application. By properly modeling your data, you can ensure that it is organized, efficient, and easy to work with. 

We discussed the importance of data modeling in NodeJS applications and provided an overview of the different techniques and tools that can be used to model data in NodeJS, including Relational data modeling, NoSQL data modeling, and Object-Relational Mapping (ORM) libraries such as Mongoose and Sequelize. Additionally, we discussed Amplication’s React Admin UI, an open source tool that can help developers create data models for their NodeJS apps quickly and easily. 

By following the steps outlined in this blog post, you can create a data model that is intuitive, maintainable and reliable to ensure the scalability and performance of the application.