Sequelize:需要vs导入

时间:2014-10-17 20:12:45

标签: node.js sequelize.js

在sequlize的文档中,他们使用像这样的导入函数

// in your server file - e.g. app.js
var Project = sequelize.import(__dirname + "/path/to/models/project")

// The model definition is done in /path/to/models/project.js
// As you might notice, the DataTypes are the very same as explained above
module.exports = function(sequelize, DataTypes) {
  return sequelize.define("Project", {
    name: DataTypes.STRING,
    description: DataTypes.TEXT
  })
}

然而,这会有什么不妥?

// in your server file - e.g. app.js
var Project = require(__dirname + "/path/to/models/project")

// The model definition is done in /path/to/models/project.js
  var Project = sequelize.define("Project", {
    name: Sequelize.STRING,
    description: Sequelize.TEXT
  });
module.exports = Project

2 个答案:

答案 0 :(得分:8)

嗯,正如您所看到的,您的模型定义需要两件事:

  1. Sequelize或DataTypes
  2. sequelize
  3. 在使用sequelize.import('something');时的第一个示例中,它类似于使用require('something')(this, Sequelize); sequelize 实例)

    两者都是初始化模型所必需的,但重要的是要理解:其中一个是classtype,因此它是全局的,另一个是实例,必须使用连接参数创建。 / p>

    所以,如果你这样做:

     var Project = sequelize.define("Project", {
        name: Sequelize.STRING,
        description: Sequelize.TEXT
      });
    module.exports = Project
    

    sequelize来自哪里?它必须以某种方式实例化并通过。

    以下是require而不是import的示例:

    // /path/to/app.js
    var Sequelize = require('sequelize');
    var sequelize = new Sequelize(/* ... */);
    var Project = require('/path/to/models/project')(sequelize, Sequelize);
    
    // /path/to/models/project.js
    module.exports = function (sequelize, DataTypes) {
        sequelize.define("Project", {
           name: DataTypes.STRING,
           description: DataTypes.TEXT
        });
    };
    
    module.exports = Project
    

    您甚至可以更改它,因此您不必通过在模型中要求它来传递 Sequelize ,但您仍需要创建 sequelize 在定义模型之前的实例。

答案 1 :(得分:0)

sequelize.import 自续集 6 起已弃用

https://sequelize.org/master/manual/models-definition.html

所述 <块引用>

已弃用:sequelize.import

注意:您不应该使用 sequelize.import。请使用 require 代替。

所以你应该只是移植:

// index.js
const sequelize = new Sequelize(...)
const User = sequelize.import('./user')

// user.js
module.exports = (sequelize, DataTypes) => {
  // Define User.
  return User;
}

到:

// index.js
const sequelize = new Sequelize(...)
const User = require('./user')(sequelize)

// user.js
const { DataTypes } = require('sequelize')
module.exports = (sequelize) => {
  // Define User.
  return User;
}