gpt4 book ai didi

javascript - 来自另一个文件的模型返回值不适用于 Sequelize.js

转载 作者:行者123 更新时间:2023-12-03 22:40:31 27 4
gpt4 key购买 nike

我有以下代码目前不起作用。

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 命令。我的猜测是变量不能以某种方式正确传递。我不确定我做错了什么?

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
}

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

enter image description here

请注意,此时我只是在变量上运行 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);
});

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

最佳答案

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

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 是在创建之前触发的,因为创建是异步发生的。这意味着我的所有代码都必须不断地通过回调运行……这似乎有点像一场噩梦。请问有没有更好的办法?

关于javascript - 来自另一个文件的模型返回值不适用于 Sequelize.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48375367/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com