Express.js and MySQL model + validation Express.js and MySQL model + validation express express

Express.js and MySQL model + validation


There is no best way to make models based on MySQL. You could implement your own way to handle models, but there are many ORM modules available for Node.js, I'd suggest using one of those.

I use Sequelize as ORM to define models and interact with the database in several Express applications. Another ORM for Node that I've run into is Bookshelf.js, but there are many others. Wich one to use depends on your preferences and necessities.

EDIT: Example of usage

I suggest the following structure when using Sequelize models: a directory in your project named models with a file for each model and an index.js file to load the Sequelize environment. If you use the Sequelize CLI, it also has several methods that follow this structure.

index.js

const fs = require("fs");const path = require("path");const Sequelize = require("sequelize");let sqize = new Sequelize({  host     : "1.2.3.4",  port     : 1234,  database : "testDb",  username : "pino",  password : "th1S1s@c0mpL3xP4sSw0rD",  dialect: 'mysql',});fs.readdirSync(__dirname).filter(function(file) {  return (file.indexOf(".") !== 0) && (file !== "index.js");}).forEach(function(file) {  let model = sequelize.import(path.join(__dirname, file));  db[model.name] = model;});Object.keys(db).forEach(function(modelName) {  if ("associate" in db[modelName]) {    db[modelName].associate(db);  }});db.sequelize = sequelize;db.Sequelize = Sequelize;db.op        = Sequelize.Op;module.exports = {  sqize: sqize,  Sequelize: Sequelize,  op: Sequelize.Op};

users.js

module.exports = function (sequelize, DataTypes) {  let users = sequelize.define('users', {    username: {      type: DataTypes.STRING(255),      allowNull: true    },    firstname: {      type: DataTypes.STRING(255),      allowNull: true    },    secondname: {      type: DataTypes.STRING(255),      allowNull: true    },    email: {      type: DataTypes.STRING(255),      allowNull: true    },    type: {      type: DataTypes.INTEGER(4),      allowNull: true,      references: {        model: 'users_type',        key: 'id'      }    },    password: {      type: DataTypes.STRING(255),      allowNull: true    },    salt: {      type: DataTypes.STRING(255),      allowNull: true    }  }, {    tableName: 'users'  });  users.associate = function (models) {    users.belongsTo(models.user_types, {      foreignKey: "type",      as: "userType"    });    users.hasMany(models.user_logs, {      foreignKey: "user_id",      as: "userLogs"    });  };  return users;};

For more parameters and details, you can check the Sequelize doc, which is very simple and full of examples and details.

Also, I've used some ECMAScript 6, so change or transpile this code if your version of Node.js does not support them.