Express.js 和 MySQL 模型 + 验证 [英] Express.js and MySQL model + validation

查看:66
本文介绍了Express.js 和 MySQL 模型 + 验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Node.js 和 Express 框架开发应用程序.我发现了很多使用 MongoDB 建模数据的例子,但我的项目需要 SQL 数据库.

I am developing application using Node.js and Express framework. I found many examples of modeling data using MongoDB, but my project requires SQL database.

谁能简单解释一下,基于 MySQL 制作模型的最佳方法是什么?

Could someone make simple explanation, what is the best way to make models based on MySQL?

我还想知道如何提供这些模型的后期验证.也许我应该在每个属性中定义验证属性?

Also I am wondering how to provide later validation of those models. Maybe I should define validation attributes inside each of them?

推荐答案

没有最好的方法来制作基于 MySQL 的模型.您可以实现自己的模型处理方式,但有许多可用于 Node.js 的 ORM 模块,我建议使用其中之一.

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.

我使用 Sequelize 作为 ORM 来定义模型并在多个 Express 应用程序中与数据库交互.我遇到的另一个 Node ORM 是 Bookshelf.js,但还有很多其他的.使用哪一种取决于您的喜好和需要.

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.

用法示例

在使用 Sequelize 模型时,我建议采用以下结构:项目中名为 models 的目录,每个模型都有一个文件,还有一个用于加载 Sequelize 环境的 index.js 文件.如果你使用 Sequelize CLI,它也有几种方法遵循这种结构.

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;
};

更多参数和细节,可以查看Sequelize doc,非常简单,示例和细节丰富.

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

此外,我使用了一些 ECMAScript 6,因此如果您的 Node.js 版本不支持它们,请更改或转译此代码.

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

这篇关于Express.js 和 MySQL 模型 + 验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆