Why Sequelize migration create table but models can not connect to a database

前端 未结 1 363
误落风尘
误落风尘 2021-01-26 02:27

I am learning how to use Sequelize ORM in Nodejs and save data in Postgres Database.

My goal is to insert user data into Users table. I have created the

相关标签:
1条回答
  • 2021-01-26 03:08

    Guyz, I found an answer to my problem,

    in models/index.js

    I change process.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;
    

    Further Details

    package.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, Let's say if I start the server by typing in the terminal

    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() remove whitespace from both sides of a string

    You want more resource? please visit w3c

    0 讨论(0)
提交回复
热议问题