javascript - Sequelize 可以创建表格,但我无法插入或选择任何内容
问题描述
我正在使用 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.
应用程序.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
}
}
您的支持是极大的赞赏。
解决方案
findAll 返回一个承诺,而您没有解决该承诺。 https://sequelize.org/master/class/lib/model.js~Model.html#static-method-findAll
在Student.findAll()上调用.then或在中间件上使用 async/await。
推荐阅读
- typescript - TypeScript - 函数断言的窄类型
- python - 如何掷骰子
- r - 给定 R 中的一组约束,如何优化多个目标/变量?
- android - 带有 RxJava3 的房间
- html - 我可以根据特定的数组名动态检查当前的单选按钮数组吗?
- javascript - 如何按对象键和值过滤对象?
- react-native - React Native,不理解调用firebase的异步函数流
- node.js - 等待循环 NodeJS 中的每个元素执行 findOneAndDelete 方法
- flutter - 我无法在 Dart 中将调整大小的 Image 对象转换为 Base64 字符串
- firebase - 颤振谷歌服务插件