mysql - Sequelize ORM 连接干净退出

标签 mysql node.js express orm sequelize.js

我是 Sequelize 新手,我正在尝试使用它来创建基本的 crud api。我正在使用 npm 包的 ^5.21.2 版本。

当我使用node或nodemon尝试在本地运行我的服务器时,nodemon给我:

[nodemon] starting `node server.js`
[nodemon] clean exit - waiting for changes before restart
[nodemon] restarting due to changes..."

我不确定为什么这种情况不断发生,但只有当我有“db.sequelize.sync...”包装函数时才会发生。我无法弄清楚需要更改什么才能实现持续的数据库连接。

db.sequelize.sync(syncOptions).then(function() {
  app.listen(PORT, console.log("==> 🌎  Listening on port %s.", PORT));
});

我的开发配置如下:

 "development": {
        "username": "root",
        "password": "*Password*",
        "database": "planit",
        "host": "127.0.0.1",
        "dialect": "mysql",
        "operatorsAliases": "false"
      }

这是我的模型索引

"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;
db.Sequelize = Sequelize;

module.exports = db;

最佳答案

问题出在这段代码上:

db.sequelize.sync(syncOptions).then(function() {
  app.listen(PORT, console.log("==> 🌎  Listening on port %s.", PORT));
});

删除 app.listen(PORT, console.log("==> 🌎 监听端口 %s.", PORT));

app.listen(PORT, console.log("==> 🌎  Listening on port %s.", PORT));
db.sequelize.sync(syncOptions).then(function() {});

关于mysql - Sequelize ORM 连接干净退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58826874/

相关文章:

MySQL - 如何在句子的一列中搜索完全匹配的单词?

mysql - 将纬度、经度的 MYSQL 5.7 点表示形式插入表中

javascript - new Date(...) 向前添加一个月

node.js - 测试 Mongo 的数据生成器?

php - Laravel MySQL whereIn 关闭不按预期工作

python - 安装 MySQL-python

node.js - 导出动态变量

node.js - 监听 EADDRINUSE:地址已在使用中:::5000

javascript - 在没有模型 :generate? 的情况下在 Sequelize 中创建新模型

node.js - MathJax 与 Node 部分