【问题标题】:Data store in wrong table after using Node Express route使用 Node Express 路由后数据存储在错误的表中
【发布时间】:2020-04-01 23:39:00
【问题描述】:

我使用 node js 和 express 作为后端,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}!`));

【问题讨论】:

    标签: express model sequelize.js express-router


    【解决方案1】:

    您的导入存在很大问题。请注意:

    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})
    

    【讨论】:

    • 谢谢先生@i.brod.it有帮助
    • 对不起,我的小问题。当我发布课程请求时,它显示了TypeError: Course is not a constructor
    • 看我的编辑。给你一个题外话提示:当你发布一个关于JS的问题时,选择javascript作为问题标签之一,这样代码就会有颜色
    • courseRoutes.post("/", async (req, res, next) => { try { const model = await Course.create(req.body); const entry = await model.save(); res.json(entry); } catch (error) { if (error.name === "ValidationError") { res.status(422); } next(error); } }); 我得到了错误:TypeError: Course.create is not a function
    • 不不,您不需要其他查询。 “模型”只是我给查询返回的对象的名称......你可以在那里获得新的 ID。删除您的第二个查询
    猜你喜欢
    • 2018-01-10
    • 2014-08-07
    • 2016-06-27
    • 2016-06-10
    • 1970-01-01
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多