Nodejs with Sequelizejs using separate files per model

前端 未结 2 1987
情书的邮戳
情书的邮戳 2021-02-05 16:48

This is an embarrassingly beginner question, but I just want to settle my worries about Sequelizejs. I want to split out each model into its own file to keep my source organize

2条回答
  •  有刺的猬
    2021-02-05 17:05

    Every model is defined as its own module, which you export:

    module.exports = function(sequelize, DataTypes){
        return sequelize.define('Brand', {
            name: {
                type: DataTypes.STRING,
                unique: true,
                allowNull: false },
            description: {
                type: DataTypes.TEXT,
                allowNull: false },
            status: {
                type: DataTypes.INTEGER,
                unique: false,
                allowNull: true }
        })
    };
    

    Then simply import the module when you initialize Sequelize (and you can import many models here):

    var Sequelize = require("sequelize");
    var config = require("../../config/config.js");
    var sequelize = new Sequelize(config.database, config.username, config.password,
        { dialect: config.dialect, host: config.host, port: config.port,
          omitNull: true, logging: false });
    var Brand = require("./Brand").Brand;
    

    You can read up more on modules at http://nodejs.org/api/modules.htm but the example above should get you started.

提交回复
热议问题