【问题标题】:How can "sequelize.import()" import models from another file?“sequelize.import()”如何从另一个文件导入模型?
【发布时间】:2017-03-31 04:48:46
【问题描述】:

当我通过以下方式创建新模型时:

//user.js file
module.exports = function (sequelize, DateTypes) {

return sequelize.define("user", {
    email: {
        type: DateTypes.STRING,
        allowNull: false,
        unique: true,
        validate: {
            isEmail: true
        }
    },
    password: {
        type: DateTypes.STRING,
        allowNull: false,
        validate: {
            len: [7, 100]
        }
    }
});
};

进入我构建新数据库的 db.js 文件:

var Sequelize = require('sequelize');
var env = process.env.NODE_ENV || "development"; // established if you work in production or in development mode
var sequelize;

if (env == "production") {
    sequelize = new Sequelize(process.env.DATABASE_URL, {
        "dialect": "postgres",

    });
} else {
    var sequelize = new Sequelize(undefined, undefined, undefined, {
        'dialect': 'sqlite',
        'storage': __dirname + '/data/dev-todo-api.sqlite' // location where you create a new sqlite database 
    });
}

var db = {};

db.todo = sequelize.import(__dirname + "/models/todo.js");
db.user = sequelize.import(__dirname + "/models/user.js");
db.sequelize = sequelize; //contain a settings of database
db.Sequelize = Sequelize;

module.exports = db;

我不明白 user.js 如何知道sequelize(我作为参数插入module.exports)是位于另一个文件中的sequelize 包的实例?可能是因为sequelize.import('/user.js') 导入了整个sequelize 包?

【问题讨论】:

  • 请检查您的拼写。在第一行你有两个错误。
  • 谢谢...我从你的问题中得到了我的解决方案:)

标签: javascript node.js sequelize.js


【解决方案1】:

sequelize.import的定义:

Sequelize.prototype.import = function(path) {
  // is it a relative path?
  if(Path.normalize(path) !== Path.resolve(path)){
    // make path relative to the caller
    var callerFilename = Utils.stack()[1].getFileName()
      , callerPath = Path.dirname(callerFilename);

    path = Path.resolve(callerPath, path);
  }

  if (!this.importCache[path]) {
    var defineCall = (arguments.length > 1 ? arguments[1] : require(path));
    if (typeof defineCall === 'object' && defineCall.__esModule) {
      // Babel/ES6 module compatability
      defineCall = defineCall['default'];
    }
    this.importCache[path] = defineCall(this, DataTypes);
  }

  return this.importCache[path];
};

实际上,它在路径上调用require,然后以sequelize 实例作为其第一个参数调用结果。这就是使模块能够引用导入它的 sequelize 实例的原因。

【讨论】:

  • 然后,使用“sequelize.import()”,是如何使用“require”将模型接收到 user.js 但“sequelize.import()”的“sequelize”是传入路径文件。对吗?
  • require(path)(this, DataTypes) 有效发生时会发生这种情况。
  • @DanD。一个相关问题:当​​我尝试访问模型文件之外的模型上定义的prototype 方法时,例如在我的控制器中,我得到Model.prototype.Yourfunction 不是函数。你能帮忙吗?如果您需要更多信息,这里有一个详细的问题:stackoverflow.com/questions/51382550/…
  • sequalize.import 现在已弃用,现在该怎么做,要求它不能正常工作
  • @ShreyanMehta sequalize.import is deprecated now 你能提供源代码吗?因为我最近使用 sequelize/cli sequelize init 生成带有 sequalize.import 的代码
【解决方案2】:

可能会有所帮助。这就是我编译时代码的样子:

/**
 * Imports a model defined in another file
 *
 * Imported models are cached, so multiple calls to import with the same path will not load the file multiple times
 *
 * See https://github.com/sequelize/express-example for a short example of how to define your models in separate files so that they can be imported by sequelize.import
 * @param {String} path The path to the file that holds the model you want to import. If the part is relative, it will be resolved relatively to the calling file
 * @return {Model}
 */
import(path) {
  // is it a relative path?
  if (Path.normalize(path) !== Path.resolve(path)) {
    // make path relative to the caller
    const callerFilename = Utils.stack()[1].getFileName();
    const callerPath = Path.dirname(callerFilename);

    path = Path.resolve(callerPath, path);
  }

  if (!this.importCache[path]) {
    let defineCall = arguments.length > 1 ? arguments[1] : require(path);
    if (typeof defineCall === 'object') {
      // ES6 module compatibility
      defineCall = defineCall.default;
    }
    this.importCache[path] = defineCall(this, DataTypes);
  }

  return this.importCache[path];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 2015-02-02
    • 2021-03-21
    • 1970-01-01
    • 2014-11-22
    • 2015-12-12
    • 2014-07-24
    相关资源
    最近更新 更多