【问题标题】:Sequelize can create tables, but I can't insert or select anythingSequelize 可以创建表格,但我无法插入或选择任何内容
【发布时间】:2021-10-16 21:54:28
【问题描述】:

我正在使用 Sequelize 创建一个具有基本 MVC 功能的快速应用程序。

现在我正在实现将一行学生数据插入数据库的路由。当服务器启动时,对强制同步表进行续集,一切看起来都很好。我可以确认数据库存在并且 Sequelize 刚刚在其中创建了学生表。

然后我使用 CL 手动插入一行。

mysql> insert into students values(1,'Alan','Johnson');

现在:

  • 服务器正在监听,
  • 数据库已创建,
  • Sequelize 能够看到模块,然后创建相应的表。
  • 该表包含手动播种的一行。

我的问题是这样的:

  • 我感觉 connection.js 没有找到 .env 文件。
  • 但是,如果 sequelize.sync 能够在数据库中创建一个表,这怎么可能呢?你能帮我找出问题所在:
    • http://localhost:3001/api/insertStudent
    • http://localhost:3001/api/Allstudents

注意:

I am using that route just to get to the Student.create() and Student.findAll() command.

app.js

const express = require('express');
const sequelize = require('./config/connection');
const path = require('path');
const router = require('./routes/index');
const PORT = process.env.PORT || 3001;
const app = express();

app.use(express.json());
app.use(router);


sequelize.sync({force: true}).then(
    app.listen(PORT, () => {
        console.log('Sever running on port: %j', PORT);
        console.log('http://localhost:%j/', PORT);
        console.log('http://localhost:%j/api/', PORT);
        console.log('http://localhost:%j/api/Allstudents', PORT);
        console.log('http://localhost:%j/api/insertStudent', PORT);
    })
);

package.json

{
  "name": "Project-2-connection-test",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "dependencies": {
    "dotenv": "^10.0.0",
    "express": "^4.17.1",
    "find-config": "^1.0.0",
    "mysql2": "^2.3.0",
    "sequelize": "^6.6.5",
    "sequelize-cli": "^6.2.0"
  },
  "devDependencies": {},
  "scripts": {
    "start": "node app.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

.env

DB_NAME="student_behavior_db"
DB_USER="root"
DB_PASSWORD=

路由/index.js

const router = require('express').Router();
const student_routes = require('./myApi/studentRoutes');
router.use('/api',student_routes);

router.get('/',(req,res)=>{
    res.status(200).send('<h1>Home root</h1>');
})

module.exports = router;

路由/Myapi/index.js

const router = require('express').Router();
const {Student} = require('../../models/index');

/* ----------------------------------------------------------------------NOT WORKING */
router.get('/allStudents', (req, res) => {
    try {
        const students = Student.findAll();
        console.log("---> students :" + JSON.stringify(students));
        return res.status(200).json(students);
    } catch (e) {
        return res.status(500).send(e.message);
    }
});
/* ----------------------------------------------------------------------NOT WORKING */
router.get('/insertStudent', (req, res) => {
     console.log("---> insertStudent :" );
    const  studentInsert  = Student.create({id:2,firstName:"John",lastName:"Stevens"})
     console.log("---> studentInsert :" + studentInsert );
        res.status(200).json(studentInsert);
})

router.get('/', (req, res) => {
    res.status(200).send('<h1>Root on student-routes</h1>');
})

module.exports = router;

models/student.js

const {Model, DataTypes} = require('sequelize');
const sequelize = require('../config/connection');


class Student extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
        // define association here
    }
};
Student.init({
    id: {type: DataTypes.INTEGER, primaryKey: true},
    firstName: {type: DataTypes.STRING, allowNull: false},
    lastName: {type: DataTypes.STRING, allowNull: false}
}, {
    sequelize,
    timestamps: false,
    modelName: 'Student',
});

module.exports = Student;

模型/index.js

const Student = require('./Student');

module.exports = {Student};

db/schema.sql

DROP DATABASE IF EXISTS student_behavior_db;
CREATE DATABASE student_behavior_db;

config/connections.js

 const Sequelize = require('sequelize');
require('dotenv').config();

const sequelize = new Sequelize(
    process.env.DB_NAME,
    process.env.DB_USER,
    process.env.DB_PASSWORD,
    {
        host: 'localhost',
        dialect: 'mysql',
        port: 3306,
    }
);

module.exports = sequelize;

config/config.json

{
  "development": {
    "host": "127.0.0.1",
    "dialect": "mysql",
    "port": 3306
  },
  "test": {
    "host": "127.0.0.1",
    "dialect": "mysql",
    "port": 3306
  },
  "production": {
    "host": "127.0.0.1",
    "dialect": "mysql",
    "port": 3306
  }
}

非常感谢您的支持。

【问题讨论】:

    标签: javascript mysql node.js express sequelize.js


    【解决方案1】:

    findAll 返回一个承诺,而您并没有解决该承诺。 https://sequelize.org/master/class/lib/model.js~Model.html#static-method-findAll

    Student.findAll() 上调用 .then 或在中间件上使用 async/await。

    【讨论】:

      猜你喜欢
      • 2016-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      相关资源
      最近更新 更多