Creating a Database Model in a FeathersJS Service | MySQL | FeathersJS Series | Part - 4

Less than 500 views


In Part - 2 of the series we discussed how to make a database connection with our feathersjs app and in Part - 3 of the series we discussed how to create a service in feathersjs.

In this part of the series, we are going to discuss how to define a MySQL database model in our feathersjs service model.js file.

Note: The name of the database table and feathersjs service is the same.

Let us suppose that we have the following MySQL database table and we are required to model it into a feathersjs model.

The table - 'test_service' has the following fields -

  1. id - int, primary key, auto_increment
  2. name - varchar(255)
  3. email - varchar(255)
  4. about - text
  5. mobile - mediumint
  6. job_title - text

The above fields and their SQL datatypes have their corresponding syntax in sequelize. And they are as follows -

Field - id

id: {
  type: DataTypes.INTEGER,
  primaryKey: true,
  autoIncrement: true,
  allowNull: false
}

Field - name

name: {
  type: DataTypes.STRING(255),
  allowNull: true
}

Field - email

email: {
  type: DataTypes.STRING(255),
  unique: true,
  allowNull: true
}

Field - about

about: {
  type: DataTypes.TEXT,
  allowNull: true
}

Field - mobile

mobile: {
  type: DataTypes.INTEGER,
  allowNull: true
}

Field - job_title

job_title: {
  type: DataTypes.STRING,
  allowNull: true
}

The above fields can be combined into a single feathersjs model for the table test_service.

Also if you take a look in the model below, the timestamps are false, which means when new data will be created in the table, there will be no created_at and updated_at fields in the table. If you want to include them also, you need to turn it to true and add these two new data fields in the model.

Hence, we built our service model. We can now very easily read and write from the database through our service. We have taken a very small example of only int and text datatypes. Other than this, we can also have Boolean, DateTime, Blob fields in our table and model.

This was it for Part - 4. I Hope that you find it to be useful. If you have anything else to say or add, let us know in the comment section below.


Author

Srajan Gupta

I am a Blogger and a Product Enthusiast. I wish this website provides you with a lot of useful content. Would love to get feedbacks on them, anytime.


Let's Connect on Social Media
What are your thoughts?
Let's Connect on Social Media