0

I am using node js and express for the backend, REST API and database is Postgresql. I am using Sequelize for connection and models. I have created two models, one is a student and another is a course. I tested my app by using POSTMAN and everything works fine as expected. Instead of putting all code in Express, I have decided to use Express routes. Now when I am testing my app via POSTMAN after using the routes. My data is store in different tables. For example: If I post the student data it stored in course table. I don't know what I am doing wrong. I know I making some silly mistake, I just I can't see it.

This is my data models and connection

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;

This student route

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;

This is course model

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;

This is express server

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}!`));
babla19830
  • 77
  • 1
  • 1
  • 10

1 Answers1

0

You have a big problem with your imports. Notice this:

module.exports = Student;
module.exports = Course;

const Student = require("./db");
const Course = require("./db");

You're exporting Student as a single export, and then overwriting it with Course. What you meant to do is:

module.exports = {
   Student,
   Course
};

const {Student,Course} = require("./db");

Don't know if this is the only problem, but it's a big one. Fix this and tell me if the issue is resolved.

Edit:regarding your second issue:

const logs = new Course(req.body);
const entry = await logs.save();

change this to this:

const model= await Course.create(req.body);

Another edit:

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
  • 3,993
  • 11
  • 38
  • 74
  • Thank you sir @i.brod.it helps – babla19830 Apr 01 '20 at 15:02
  • Oh sorry I tiny issue. When I post course request it showed me `TypeError: Course is not a constructor` – babla19830 Apr 01 '20 at 15:19
  • look at my edit .An offtopic tip for you: When you post a question about JS, select javascript as one of the question tags, so that the code will have colors – i.brod Apr 01 '20 at 15:23
  • `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); } });` and I got error: `TypeError: Course.create is not a function` – babla19830 Apr 01 '20 at 15:28
  • No no, you don;t need another query. "model" is just the name i gave to the object that is returned by the query...you can get the new ID there. remove your second query – i.brod Apr 01 '20 at 15:34
  • I dont have an account there...ill update my answer – i.brod Apr 01 '20 at 15:38
  • Just one question, If I can post students logic why I can't get the same on Course. does not make any sense to me? – babla19830 Apr 01 '20 at 15:38
  • I don't know. maybe your models are setup differently. I never used Sequelize with this new modelName() way you're using. – i.brod Apr 01 '20 at 15:40
  • Also it works on me, When I put all the codes in Express sever. After using routes, I am getting error. Something I am missing. Which I can't get it – babla19830 Apr 01 '20 at 15:42
  • But what doesn't work now? have you looked at my edit? – i.brod Apr 01 '20 at 15:46
  • sir, I fixed my problem, When I import Couse. I just use `const { Course } = require("./db");` – babla19830 Apr 01 '20 at 15:46
  • Thank you sir @i.brod – babla19830 Apr 01 '20 at 15:50