gpt4 book ai didi

express - 使用 Node Express 路由后数据存储在错误的表中

转载 作者:行者123 更新时间:2023-12-03 22:35:45 24 4
gpt4 key购买 nike

我使用 node js 和 express 作为后端,REST API 和数据库是 Postgresql。我正在使用 Sequelize 进行连接和模型。我创建了两个模型,一个是学生,另一个是类(class)。我使用 POSTMAN 测试了我的应用程序,一切正常。我决定使用 Express 路由,而不是将所有代码都放在 Express 中。现在,当我在使用路由后通过 POSTMAN 测试我的应用程序时。我的数据存储在不同的表中。例如:如果我发布它存储在类(class)表中的学生数据。我不知道我做错了什么。我知道我犯了一些愚蠢的错误,只是我看不到。

这是我的数据模型和连接

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;

这是类(class)模型
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})

关于express - 使用 Node Express 路由后数据存储在错误的表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60965479/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com