0

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

这是我的数据模型和连接

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}!`));
4

1 回答 1

0

你的进口有很大的问题。请注意:

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})
于 2020-04-01T14:11:44.770 回答