首页 > 解决方案 > Sequelize 可以创建表格,但我无法插入或选择任何内容

问题描述

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

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

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

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

现在:

我的问题是这样的:

笔记:

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

应用程序.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);
    })
);

包.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;

模型/学生.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};

数据库/schema.sql

DROP DATABASE IF EXISTS student_behavior_db;
CREATE DATABASE student_behavior_db;

配置/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.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
  }
}

您的支持是极大的赞赏。

标签: javascriptmysqlnode.jsexpresssequelize.js

解决方案


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

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


推荐阅读