使用 Node Express 路由后数据存储错误 table
Data store in wrong table after using Node Express route
我正在使用节点 js 和 express 作为后端,REST API 数据库是 Postgresql。我正在使用 Sequelize 进行连接和建模。我创建了两个模型,一个是学生,另一个是课程。我使用 POSTMAN 测试了我的应用程序,一切正常。我决定使用 Express 路由,而不是将所有代码都放在 Express 中。现在,当我在使用路由后通过 POSTMAN 测试我的应用程序时。我的数据存储在不同的 table 中。例如:如果我 post 它存储在课程 table 中的学生数据。我不知道我做错了什么。我知道我犯了一些愚蠢的错误,只是我看不到而已。
这是我的数据模型和连接
const sequelize = require("sequelize");
var con = new sequelize("school", "postgres", "password", {
host: "localhost",
dialect: "postgres",
pool: {
max: 5,
min: 0,
idle: 10000
}
});
const Student = con.define("student", {
id: {
type: sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
unique: true
},
name: {
type: sequelize.STRING,
allowNull: false
},
birthday: {
type: sequelize.DATEONLY,
allowNull: false
},
address: {
type: sequelize.STRING,
allowNull: false
},
zipcode: {
type: sequelize.INTEGER,
allowNull: false
},
city: {
type: sequelize.STRING,
allowNull: false
},
phone: {
type: sequelize.BIGINT,
allowNull: false,
unique: true
},
email: {
type: sequelize.STRING,
allowNull: false,
unique: true,
validate: {
isEmail: true
}
}
});
const Course = con.define("course", {
id: {
type: sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: { type: sequelize.STRING },
startdate: { type: sequelize.DATEONLY },
enddate: { type: sequelize.DATEONLY },
studentId: { type: sequelize.INTEGER, foreignKey: true }
});
Student.hasMany(Course);
Course.belongsTo(Student);
//con.sync({ force: true });
module.exports = Student;
module.exports = Course;
这条学生路线
const express = require("express");
const studentRoute = express.Router();
const Student = require("./db");
const Course = require("./db");
studentRoute.get("/", async (req, res, next) => {
try {
await Student.findAll({
include: [
{
model: Course
}
]
}).then(docs => {
const response = {
count: docs.length,
students: docs
};
res.json(response);
});
} catch (error) {
console.log(error);
}
});
studentRoute.get("/:id", async (req, res, next) => {
const id = req.params.id;
try {
Student.findByPk(id).then(data => {
console.log(data);
res.json(data);
});
} catch (error) {
console.log(error);
}
});
studentRoute.put("/:id", async (req, res) => {
const id = req.params.id;
const update = req.body;
try {
await Student.update(update, { where: { id } }).then(data => {
res.json(data);
});
} catch (error) {
console.log(error);
}
});
studentRoute.delete("/:id", async (req, res, next) => {
const id = req.params.id;
try {
Student.destroy({ where: { id } }).then(data => {
res.json(data);
});
} catch (error) {
console.log(error);
}
});
studentRoute.post("/", async (req, res, next) => {
try {
const logs = new Student(req.body);
const entry = await logs.save();
res.json(entry);
} catch (error) {
if (error.name === "ValidationError") {
res.status(422);
}
next(error);
}
});
module.exports = studentRoute;
这是课程模型
const express = require("express");
const courseRoutes = express.Router();
const Course = require("./db");
courseRoutes.get("/", async (req, res, next) => {
try {
await Course.findAll().then(docs => {
const response = {
count: docs.length,
courses: docs
};
res.json(response);
});
} catch (error) {
console.log(error);
}
});
courseRoutes.get("/:id", async (req, res, next) => {
const id = req.params.id;
try {
Course.findByPk(id).then(data => {
console.log(data);
res.json(data);
});
} catch (error) {
console.log(error);
}
});
courseRoutes.put("/:id", async (req, res, next) => {
const id = req.params.id;
const update = req.body;
try {
await Course.update(update, { where: { id } }).then(data => {
res.json(data);
});
} catch (error) {
console.log(error);
}
});
courseRoutes.delete("/:id", async (req, res, next) => {
const id = req.params.id;
try {
Course.destroy({ where: { id } }).then(data => {
res.json(data);
});
} catch (error) {
console.log(error);
}
});
courseRoutes.post("/", async (req, res, next) => {
try {
const logs = new Course(req.body);
const entry = await logs.save();
res.json(entry);
} catch (error) {
if (error.name === "ValidationError") {
res.status(422);
}
next(error);
}
});
module.exports = courseRoutes;
这是快速服务器
require("dotenv").config();
const express = require("express");
const app = express();
const morgan = require("morgan");
const helmet = require("helmet");
const cors = require("cors");
const studentRoute = require("./models/studentRoute");
const courseRoutes = require("./models/courseRoutes");
app.use(morgan("common"));
app.use(helmet());
app.use(cors());
app.use(express.json()); //body Parser
//Routes
app.use("/students", studentRoute);
app.use("/courses", courseRoutes);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(` App is listening at port ${port}!`));
您的导入有很大问题。请注意:
module.exports = Student;
module.exports = Course;
const Student = require("./db");
const Course = require("./db");
您正在将 Student 作为单个导出导出,然后用 Course 覆盖它。你的意思是:
module.exports = {
Student,
Course
};
const {Student,Course} = require("./db");
不知道这是否是唯一的问题,但这是一个大问题。修复此问题并告诉我问题是否已解决。
编辑:关于您的第二期:
const logs = new Course(req.body);
const entry = await logs.save();
将此更改为:
const model= await Course.create(req.body);
另一个编辑:
const model = await Course.create(req.body);//Create the record. The returned object will also contain the id, createdAt, updatedAt.
const id = model.id;//This is the new id, in case you need it in the frontend. This way you can, for instance:
res.json({id})
我正在使用节点 js 和 express 作为后端,REST API 数据库是 Postgresql。我正在使用 Sequelize 进行连接和建模。我创建了两个模型,一个是学生,另一个是课程。我使用 POSTMAN 测试了我的应用程序,一切正常。我决定使用 Express 路由,而不是将所有代码都放在 Express 中。现在,当我在使用路由后通过 POSTMAN 测试我的应用程序时。我的数据存储在不同的 table 中。例如:如果我 post 它存储在课程 table 中的学生数据。我不知道我做错了什么。我知道我犯了一些愚蠢的错误,只是我看不到而已。
这是我的数据模型和连接
const sequelize = require("sequelize");
var con = new sequelize("school", "postgres", "password", {
host: "localhost",
dialect: "postgres",
pool: {
max: 5,
min: 0,
idle: 10000
}
});
const Student = con.define("student", {
id: {
type: sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
unique: true
},
name: {
type: sequelize.STRING,
allowNull: false
},
birthday: {
type: sequelize.DATEONLY,
allowNull: false
},
address: {
type: sequelize.STRING,
allowNull: false
},
zipcode: {
type: sequelize.INTEGER,
allowNull: false
},
city: {
type: sequelize.STRING,
allowNull: false
},
phone: {
type: sequelize.BIGINT,
allowNull: false,
unique: true
},
email: {
type: sequelize.STRING,
allowNull: false,
unique: true,
validate: {
isEmail: true
}
}
});
const Course = con.define("course", {
id: {
type: sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: { type: sequelize.STRING },
startdate: { type: sequelize.DATEONLY },
enddate: { type: sequelize.DATEONLY },
studentId: { type: sequelize.INTEGER, foreignKey: true }
});
Student.hasMany(Course);
Course.belongsTo(Student);
//con.sync({ force: true });
module.exports = Student;
module.exports = Course;
这条学生路线
const express = require("express");
const studentRoute = express.Router();
const Student = require("./db");
const Course = require("./db");
studentRoute.get("/", async (req, res, next) => {
try {
await Student.findAll({
include: [
{
model: Course
}
]
}).then(docs => {
const response = {
count: docs.length,
students: docs
};
res.json(response);
});
} catch (error) {
console.log(error);
}
});
studentRoute.get("/:id", async (req, res, next) => {
const id = req.params.id;
try {
Student.findByPk(id).then(data => {
console.log(data);
res.json(data);
});
} catch (error) {
console.log(error);
}
});
studentRoute.put("/:id", async (req, res) => {
const id = req.params.id;
const update = req.body;
try {
await Student.update(update, { where: { id } }).then(data => {
res.json(data);
});
} catch (error) {
console.log(error);
}
});
studentRoute.delete("/:id", async (req, res, next) => {
const id = req.params.id;
try {
Student.destroy({ where: { id } }).then(data => {
res.json(data);
});
} catch (error) {
console.log(error);
}
});
studentRoute.post("/", async (req, res, next) => {
try {
const logs = new Student(req.body);
const entry = await logs.save();
res.json(entry);
} catch (error) {
if (error.name === "ValidationError") {
res.status(422);
}
next(error);
}
});
module.exports = studentRoute;
这是课程模型
const express = require("express");
const courseRoutes = express.Router();
const Course = require("./db");
courseRoutes.get("/", async (req, res, next) => {
try {
await Course.findAll().then(docs => {
const response = {
count: docs.length,
courses: docs
};
res.json(response);
});
} catch (error) {
console.log(error);
}
});
courseRoutes.get("/:id", async (req, res, next) => {
const id = req.params.id;
try {
Course.findByPk(id).then(data => {
console.log(data);
res.json(data);
});
} catch (error) {
console.log(error);
}
});
courseRoutes.put("/:id", async (req, res, next) => {
const id = req.params.id;
const update = req.body;
try {
await Course.update(update, { where: { id } }).then(data => {
res.json(data);
});
} catch (error) {
console.log(error);
}
});
courseRoutes.delete("/:id", async (req, res, next) => {
const id = req.params.id;
try {
Course.destroy({ where: { id } }).then(data => {
res.json(data);
});
} catch (error) {
console.log(error);
}
});
courseRoutes.post("/", async (req, res, next) => {
try {
const logs = new Course(req.body);
const entry = await logs.save();
res.json(entry);
} catch (error) {
if (error.name === "ValidationError") {
res.status(422);
}
next(error);
}
});
module.exports = courseRoutes;
这是快速服务器
require("dotenv").config();
const express = require("express");
const app = express();
const morgan = require("morgan");
const helmet = require("helmet");
const cors = require("cors");
const studentRoute = require("./models/studentRoute");
const courseRoutes = require("./models/courseRoutes");
app.use(morgan("common"));
app.use(helmet());
app.use(cors());
app.use(express.json()); //body Parser
//Routes
app.use("/students", studentRoute);
app.use("/courses", courseRoutes);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(` App is listening at port ${port}!`));
您的导入有很大问题。请注意:
module.exports = Student;
module.exports = Course;
const Student = require("./db");
const Course = require("./db");
您正在将 Student 作为单个导出导出,然后用 Course 覆盖它。你的意思是:
module.exports = {
Student,
Course
};
const {Student,Course} = require("./db");
不知道这是否是唯一的问题,但这是一个大问题。修复此问题并告诉我问题是否已解决。
编辑:关于您的第二期:
const logs = new Course(req.body);
const entry = await logs.save();
将此更改为:
const model= await Course.create(req.body);
另一个编辑:
const model = await Course.create(req.body);//Create the record. The returned object will also contain the id, createdAt, updatedAt.
const id = model.id;//This is the new id, in case you need it in the frontend. This way you can, for instance:
res.json({id})