繁体   English   中英

来自另一个文件的模型返回值无法与Sequelize.js一起使用

[英]Model return values from another file not working with Sequelize.js

我有以下当前无法使用的代码。

var config = require('./libs/sequelize-lib.js');
var connection = config.getSequelizeConnection();//Choosing to not pass in variable this time since this should only run via script.
var models = config.setModels(connection);//Creates live references to the models.

//Alter table as needed but do NOT force the change.  If an error occurs we will fix manually.
connection.sync({ alter: true, force: false }).then(function() {
  models.users.create({
    name: 'joe',
    loggedIn: true
  }).then( task => {
    console.log("saved user!!!!!");
  });
  process.exit();//close the nodeJS Script
}).catch(function(error) {
  console.log(error);
});

sequelize-lib.js

var Sequelize = require('sequelize');

exports.getSequelizeConnection = function(stage){
  var argv = require('minimist')(process.argv.slice(2)); //If this file is being used in a script, this will attempt to get information from the argument stage passed if it exists

  //Change connection settings based on stage variable.  Assume localhost by default.
  var dbname = argv['stage'] ? argv['stage']+"_db"                              : 'localdb';
  var dbuser = argv['stage'] ? process.env.RDS_USERNAME                         : 'admin';
  var dbpass = argv['stage'] ? process.env.RDS_PASSWORD                         : 'local123';
  var dbhost = argv['stage'] ? "database-"+argv['stage']+".whatever.com"  : 'localhost';

  //If state variable used during require overide any arguments passed.
  if(stage){
    dbname = stage+"_db";
    dbuser = process.env.RDS_USERNAME
    dbpass = process.env.RDS_PASSWORD
    dbhost = "database-"+stage+".whatever.com"
  }

  var connection = new Sequelize(dbname,dbuser,dbpass, {
    dialect: 'mysql',
    operatorsAliases: false, //This gets rid of a sequelize deprecated warning , refer https://github.com/sequelize/sequelize/issues/8417
    host: dbhost
  });
  return connection;
}

exports.setModels = function(connection){
  //Import all the known models for the project.
  const fs = require('fs');
  const dir = __dirname+'/../models';

  var models = {}; //empty model object for adding model instances in file loop below.

  //@JA - Wait until this function finishes ~ hence readdirSync vs regular readdir which is async
  fs.readdirSync(dir).forEach(file => {
    console.log(file);
    //Split the .js part of the filename
    var arr = file.split(".");
    var name = arr[0].toLowerCase();
    //Create a modle object using the filename as the reference without the .js pointing to a created sequelize instance of the file.
    models[name] = connection.import(__dirname + "/../models/"+file);
  })

  //Showcase the final model.
  console.log(models);

  return models; //This returns a model with reference to the sequelize models
}

我无法使用此设置来创建命令。 我的猜测是变量一定不能以某种方式正确传递。 我不确定自己在做什么错?

create命令绝对有效,因为如果在sequelize-lib.js中,我将setModels函数修改为此...

exports.setModels = function(connection){
  //Import all the known models for the project.
  const fs = require('fs');
  const dir = __dirname+'/../models';

  var models = {}; //empty model object for adding model instances in file loop below.

  //@JA - Wait until this function finishes ~ hence readdirSync vs regular readdir which is async
  fs.readdirSync(dir).forEach(file => {
    console.log(file);
    //Split the .js part of the filename
    var arr = file.split(".");
    var name = arr[0].toLowerCase();
    //Create a modle object using the filename as the reference without the .js pointing to a created sequelize instance of the file.
    models[name] = connection.import(__dirname + "/../models/"+file);
    models[name].create({
      "name":"joe",
      "loggedIn":true
    });
  })

  //Showcase the final model.
  console.log(models);

  return models; //This returns a model with reference to the sequelize models
}

然后它起作用了,我看到该项目已添加到数据库中! (请参阅下面的证明图片)

在此处输入图片说明

请注意,此时我只是在变量上运行create。 在模型对象无法正确在文件之间传递的情况下,我该怎么办? 奇怪的是我没有在主文件中抛出任何错误? 就像所有内容都已定义但为空还是什么一样,并且该命令从不运行,并且什么也没有添加到数据库中。

我也在主文件中尝试过这个,也没有运气。

models["users"].create({
    name: 'joe',
    loggedIn: true
  }).then( task => {
    console.log("saved user!!!!!");
  });

这一切的目的是自动从模型目录中读取模型,并创建可用于每种模型的实例,即使将来添加新模型也是如此。

更新::

所以我做了另一个有趣的测试,似乎create函数在sync命令的.then()函数中不起作用。 看起来好像正确传递了它。 将首页更改为此后...

var config = require('./libs/sequelize-lib.js');
var connection = config.getSequelizeConnection();//Choosing to not pass in variable this time since this should only run via script.
var models = config.setModels(connection);//Creates live references to the models using connection previosly created.

models["users"].create({
  "name":"joe",
  "loggedIn":true
});

//Alter table as needed but do NOT force the change.  If an error occurs we will fix manually.
connection.sync({ alter: true, force: false }).then(function() {
  process.exit();//close the nodeJS Script
}).catch(function(error) {
  console.log(error);
});

这样做似乎可以使创造工作。 我不确定这是否是好的形式,因为此时可能无法创建数据库? 我需要一种使其在同步功能中工作的方法。

好吧,我终于回答了我的问题,但是我不确定我是否喜欢答案。

var config = require('./libs/sequelize-lib.js');
var connection = config.getSequelizeConnection();//Choosing to not pass in variable this time since this should only run via script.
var models = config.setModels(connection);//Creates live references to the models using connection previosly created.

//Alter table as needed but do NOT force the change.  If an error occurs we will fix manually.
connection.sync({ alter: false, force: false }).then( () => {
  models["users"].create({
    "name":"joe",
    "loggedIn":true
  }).then( user => {
    console.log("finished, with user.name="+user.name);
    process.exit();
  }).catch( error => {
    console.log("Error Occured");
    console.log(error);
  });
}).catch(function(error) {
  console.log(error);
});

事实证明process.exit在创建之前就已经触发了,因为创建是异步发生的。 这意味着我所有的代码都将必须不断地通过回调运行……这似乎是一场噩梦。 我想知道是否有更好的方法?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM