为什么Sequelize迁移创建表但模型无法连接到数据库

2024-02-08

我正在学习如何在 Nodejs 中使用 Sequelize ORM 并将数据保存在 Postgres 数据库中。

我的目标是将用户数据插入Users桌子。我已经使用迁移创建了该表,并且它有效。但是,我无法保存用户数据。例如,我关注了很多资源Tut 1 https://www.duringthedrive.com/2017/05/06/models-migrations-sequelize-node/ Tut 2 https://github.com/sequelize/express-example等等,我仍然遇到同样的错误

C:\Users\HP\Desktop\path\project\Tutorials\react-project\chat_app_api\database\models\index.js:12
if (config.use_env_variable) {
           ^
TypeError: Cannot read property 'use_env_variable' of undefined
    at Object.<anonymous> (C:\Users\HP\Desktop\path\project\Tutorials\react-project\chat_app_api\database\models\index.js:12:12)
    at Module._compile (internal/modules/cjs/loader.js:776:30)
    at babelWatchLoader (C:\Users\HP\Desktop\path\project\Tutorials\react-project\chat_app_api\node_modules\babel-watch\runner.js:51:13)    
    at Object.require.extensions.(anonymous function) [as .js] (C:\Users\HP\Desktop\path\project\Tutorials\react-project\chat_app_api\node_modules\babel-watch\runner.js:62:7)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Module.require (internal/modules/cjs/loader.js:690:17)
    at require (internal/modules/cjs/helpers.js:25:18)
    at Object.<anonymous> (C:\Users\HP\Desktop\Andela\project\Tutorials\react-project\chat_app_api\server\server.js:1:1)
    at Module._compile (internal/modules/cjs/loader.js:776:30)
    at babelWatchLoader (C:\Users\HP\Desktop\path\project\Tutorials\react-project\chat_app_api\node_modules\babel-watch\runner.js:51:13)    
    at Object.require.extensions.(anonymous function) [as .js] (C:\Users\HP\Desktop\path\project\Tutorials\react-project\chat_app_api\node_modules\babel-watch\runner.js:62:7)

配置/config.js

require('dotenv').config();

module.exports = {
  development: {
    use_env_variable: 'DATABASE_URL_DEV',
    dialect: 'postgres',
  },
  test: {
    use_env_variable: 'DATABASE_URL_TEST',
    dialect: 'postgres',
  },
  production: {
    use_env_variable: 'DATABASE_URL',
    dialect: 'postgres',
    ssl: true,
    dialectOptions: {
      ssl: true,
    },
  },
};

迁移/20190927083519-create-user.js

'use strict';
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('Users', {
      id: {
        allowNull: false,
        primaryKey: true,
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV4,
      },
      fullname: {
        type: Sequelize.STRING
      },
      email: {
        type: Sequelize.STRING
      },
      password: {
        type: Sequelize.STRING
      },
      username: {
        type: Sequelize.STRING
      },
      telephone: {
        type: Sequelize.STRING
      },
      image: {
        type: Sequelize.STRING
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('Users');
  }
};

模型/index.js

'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.js')[env];        // why this return Undefined ?
const db = {};

let sequelize;
if (config.use_env_variable) {
  sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(file => {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach(file => {
    const model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

模型/用户

'use strict';
module.exports = (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
    },
    fullname: DataTypes.STRING,
    email: DataTypes.STRING,
    password: DataTypes.STRING,
    username: DataTypes.STRING,
    telephone: DataTypes.STRING,
    image: DataTypes.STRING
  }, {});
  User.associate = function (models) {
    // associations can be defined here
  };
  return User;
};

app.js

import express from 'express';
import cors from 'cors';
import morgan from 'morgan';
import bodyParser from 'body-parser';
import { errors } from 'celebrate';

import routes from './Routes/index';

const app = express();

app.use(cors());
app.use(morgan('combined'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use('/api', routes);

app.use(errors());


app.use((req, res) => {
  const error = new Error('Route not found');
  error.status = 404;
  return res.status(error.status).json({
    status: error.status,
    message: error.message,
  });
});

// Server Error
app.use((error, req, res) => {
  const status = error.status || 500;
  return res.status(status).json({
    status,
    message: error.message || 'Server error',
  });
});

export default app;

.env

DATABASE_URL_DEV=postgres://postgres:.@localhost:5432/db_dev
DATABASE_URL_TEST=postgres://postgres:.@localhost:5432/db_test
DATABASE_URL=postgres://user:password@host:5432/db_remote

控制器/userControllers.js

import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import dotenv from 'dotenv';

import models from '../../database/models';
import uploadImage from '../Helpers/upload.Image';

dotenv.config();

class UserController {
  static async signup(req, res) {
    const { body: input } = req;
    input.password = bcrypt.hashSync(input.password, 10);
    try {
      const image = await uploadImage(req, res);
      const { secure_url: img } = await image;

      input.image = img;
      console.log('result before ########################', models.User);         // Undefined
      const result = await models.User.create(input);
      console.log('result after ########################', result);                // Error here
      delete result.dataValues.password;

      const token = jwt.sign(result.dataValues, process.env.SECRET_KEY, { expiresIn: '1W' });
      result.dataValues.token = token;
      const status = 201;
      return res.status(status).json({
        status,
        message: 'User successfully created',
        data: result.dataValues,
      });
    } catch (error) {
      console.log('error########################', error);
      let { message } = error.errors[0];
      const status = 500;
      message = message || 'Server error';
      return res.status(status).json({
        status,
        message,
      });
    }
  }
}

export default UserController;

我还是不知道为什么在模型/index.js my 配置变量返回未定义。

require(__dirname + '/../config/config.js')           // return object

env                                                   // return environment

const config = require(__dirname + '/../config/config.js')[env];                //return Undefined

我花了3天的时间调试,但无法解决错误。非常感谢任何帮助、指导。

Thanks


Guyz,我找到了问题的答案,

in 模型/index.js

我改变进程.env.NODE_ENV to process.env.NODE_ENV.trim()

'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);

// Before
const env = process.env.NODE_ENV || 'development';

// After
const env = process.env.NODE_ENV.trim() || 'development';    // add .trim()

const config = require(__dirname + '/../config/config.js')[env];
const db = {};

let sequelize;
if (config.use_env_variable) {
  sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  sequelize = new Sequelize(config.database, config.username, config.password, config);
}

...

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

更多细节

包.json

"scripts": {
    "db:migrate:dev": "sequelize db:migrate --env development",
    "db:migrate:test": "sequelize db:migrate --env test",
    "db:migrate:production": "sequelize db:migrate --env production",
    "db:reset": "sequelize db:migrate:undo",
    "start": "SET NODE_ENV=production && babel-watch server/server.js",
    "dev": "SET NODE_ENV=development && babel-watch server/server.js",
    "test": "SET NODE_ENV=testing && babel-watch server/server.js"
  }

Example,假设我通过在终端中输入来启动服务器

npm run dev 
If i do console.log(process.env.NODE_ENV)  // output is "development " with a space.

Hence, 
 process.env.NODE_ENV === "development"  // return false
 or
 "development " === "development" // return false

Javascript Trim() 删除字符串两侧的空格

您想要更多资源吗?请拜访w3c https://www.w3schools.com/jsref/jsref_trim_string.asp

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么Sequelize迁移创建表但模型无法连接到数据库 的相关文章

随机推荐

  • JSHint 选项默认值的完整列表?

    我在哪里可以获得 JSHint 默认选项的完整列表 我尝试在网上搜索但找不到任何东西 编辑 我的意思是默认列表values for all选项 以防不清楚 你可以看看boolOptions valOptions and invertedOp
  • HQL 错误:连接所需的路径

    我一直在尝试这个查询的变体 但似乎无法实现这一点 我还参考了这篇文章 预计加入路径 休眠错误 https stackoverflow com questions 5759707 path expected for join nhiberna
  • C# 发送带有附件的电子邮件(图片)

    我的方法使用 SMTP 中继服务器发送电子邮件 一切正常 电子邮件已发送 除了附件 图像 以某种方式压缩 不存在并且无法从电子邮件中检索之外 该方法如下所示 public static bool SendEmail HttpPostedFi
  • GitHub API - 如何确定文件是否实际上是符号链接?

    通过 GitHub API 查询符号链接时 如果符号链接指向文件而不是目录 我会得到不同的结果 后者表现得更好 因为它会返回 type symlink 作为其 JSON 的一部分 而前者返回 type file 例子文件符号链接 https
  • 动态插入 3 个图像到水平滚动视图或 Viewpager

    下面显示了我正在寻找的图像 目前我正在使用视图寻呼机和圆圈指示器 在视图页面中 它仅显示单个图像 我想要在一个viewpager中显示三张图像 如图所示 当我滑动该页面时 再次从服务器加载三个不同的图像 并在下面显示文本 这个怎么做 对此有
  • 使用已知和未知字段反序列化 json

    给出以下 json 结果 默认的 json 结果有一组已知的字段 id 7908 name product name 但可以使用其他字段进行扩展 在本例中 unknown field name 1 and unknown field nam
  • jQuery - 选择具有特定样式的子项

    我不知道如何在以下示例中选择第一个跨度 div class sp span abc span span xyz span div 我尝试过使用这个 但没有成功 div sp span visibility hidden not work t
  • 使用 XCode 4.5 运行 iOS 5.1 模拟器时出现问题

    我最近将 XCode 升级到了 4 5 版本 现在当我尝试开发 iOS 5 0 5 1 的应用程序时遇到了问题 我开发了一个简单的 iPad 游戏 用户需要将图像与相应的单词进行匹配 所有这些项目都存储在 UIImageView 中 如果相
  • 适用于 iOS 8 和 iOS 9 的自定义 Unwind Segue

    我的问题是 如何让以下自定义展开转场在 iOS 9 之前版本的设备以及运行 iOS 9 的设备上工作 我有一个显示视图控制器的自定义 Segue 然后有一个相应的自定义展开 Segue 这段代码在 iOS 8 中运行良好 是通过创建 UIS
  • 将 jzy3d.canvas 转换为 awt.component

    我需要将 jzy3d 画布转换为 java awt component 我想使用 JCombobox 和按钮在框架中显示图表 但是当我想将画布转换为组件时 程序被删除 谢谢您的回答 我已经尝试过this https stackoverflo
  • Spring 5 WebFlux 中的缓存

    有没有办法在 Spring 5 中缓存来自 WebClient 的 Flux 我尝试过这个 但没有缓存任何东西 RestController SpringBootApplication EnableCaching public class
  • 如何标记相同的熊猫数据框行?

    我有一个像这样的大熊猫数据框 log apple watermelon orange lemon grapes 1 1 1 yes 0 0 1 2 0 1 0 0 1 True 0 0 0 2 2 0 0 0 0 2 2 1 1 yes 0
  • gcc 对 alloca 的处理是怎么回事?

    在大多数平台上 alloca只是归结为堆栈指针的内联调整 例如 从rsp在 x64 上 加上一些维护堆栈对齐的逻辑 I was looking at the code that gcc generates for alloca and it
  • paypal.HostedFields.isEligible() 始终返回 False :Paypal 借记卡/信用卡付款

    我想在我的网站上添加由 PayPal 提供支持的借记卡 信用卡付款 我正在按照指南进行操作 https developer paypal com docs business checkout advanced card payments h
  • Gdb - 打印数组或数组元素,具有各种大小的元素

    汇编代码 yasm section data src db 1 2 3 的每个元素src数组是1个字节 In GDB 如何打印整个数组或指定索引处的元素 例如打印值为 2 的元素 好的 在 Michael Petch 的许可下 我想自己给出
  • 如何在同一张图片中定位多个物体?

    我是 TensorFlow 的新手 目前 我正在TensorFlow网站上测试一些分类示例 卷积神经网络 它解释了如何将输入图像分类到预定义的类中 但问题是 我不知道如何在相同的图像 例如 我有一个带有猫和狗的输入图像 我希望我的图形在输出
  • 如何找到与输入元素最接近且处于同一级别的标签

    我动态添加input我的表单中的元素 每个逻辑代码块如下所示
  • RuntimeError:切勿在任务 Celery 中调用 result.get()

    我正在使用 celery 将任务发送到远程服务器并尝试返回结果 任务状态不断更新更新状态 http docs celeryproject org en latest reference celery app task html celery
  • 自定义静音/取消静音按钮 Youtube API

    Preface 我想说我已经尽力避免使这个问题成为重复的问题 即自己搜索谷歌 阅读很多其他类似的问题等 我发现了很多真正有用的东西 这些东西使我遇到了这种特定情况我有代码可以展示 所以希望我的最后一个问题能够清晰且可以回答 我有一个使用纯
  • 为什么Sequelize迁移创建表但模型无法连接到数据库

    我正在学习如何在 Nodejs 中使用 Sequelize ORM 并将数据保存在 Postgres 数据库中 我的目标是将用户数据插入Users桌子 我已经使用迁移创建了该表 并且它有效 但是 我无法保存用户数据 例如 我关注了很多资源T