我的模特
index.js
'use strict';
var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var basename = path.basename(module.filename);
var env = process.env.NODE_ENV || 'development';
var config = require(__dirname + '/../config/config.json')[env];
var db = {};
if (config.use_env_variable) {
var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
var sequelize = new Sequelize(config.database, config.username, config.password, config);
}
fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(function(file) {
var model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach(function(modelName) {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
module.exports = db;
course.js
'use strict';
module.exports = function(sequelize, DataTypes) {
var Course = sequelize.define('Course', {
title: DataTypes.STRING,
url: DataTypes.STRING,
downloaded: DataTypes.BOOLEAN,
date_published: DataTypes.DATEONLY
}, {
underscored: true,
classMethods: {
associate: function(models) {
// associations can be defined here
}
}
});
return Course;
};
test.js
const Course = require('./models').Course
const courses = [
{
title: 'xyz1',
url: 'https://www.example.com/xyz1'
},
{
title: 'xyz2',
url: 'https://www.example.com/xyz2'
}
]
courses.forEach(item => Course.create(item).then(course => {}))
My Problem:
现在,当运行node test.js
时,代码后不会退出 执行。
答案 0 :(得分:0)
Try rewriting your code as -
const db = require('./models');
const Course = db.Course;
const courses = [
{
title: 'xyz1',
url: 'https://www.example.com/xyz1'
},
{
title: 'xyz2',
url: 'https://www.example.com/xyz2'
}
];
function _createCourses(courseList) {
courseList.forEach(course => {
Course.create(course).then(createdCourse => {
console.log(createdCourse.get({
plain: true
}));
});
});
}
db.sequelize.sync()
.then(() => {
_createCourses(courses);
});
The only difference here is we are calling sequalize.sync
before creating the model objects. sync
actually syncs all defined models in db. Check out the documentation for details - sequalize.sync
答案 1 :(得分:0)
当我们从命令行运行脚本时,sequelize连接池未关闭,这就是为什么我们需要调用sequelize.close()
(http://docs.sequelizejs.com/manual/tutorial/upgrade-to-v4.html#general)来关闭已完成作业的缓冲池或运行{{ 1}}也会杀死池。
在节点中直到完成所有工作为止,例如,侦听某事或任何process.exit()
的事件,或者像此处的任何连接打开(套接字连接)执行都不会完成。这就是为什么执行还没有完成的原因。