0
votes

I'm trying to insert a student in my table 'students' but I have the following error:

Executing (default): INSERT INTO "students" ("id","created_at","updated_at") VALUES (DEFAULT,$1,$2) RETURNING *; (node:6582) UnhandledPromiseRejectionWarning: SequelizeDatabaseError: null value in column "name" violates not-null constraint

I'm using Node.js + Sequelize (Postgres).

Here's my code:

Student.js (Model)

import Sequelize, { Model } from 'sequelize';

class Student extends Model {
   static init(sequelize) {
      super.init(
         {
            name: Sequelize.STRING,
            email: Sequelize.STRING,
            age: Sequelize.INTEGER,
            weight: Sequelize.DECIMAL(10, 2),
            height: Sequelize.DECIMAL(10, 2),
         },
         {
            sequelize,
         }
      );
   }
}

export default Student;

StudentController.js (Controller)

import Student from '../models/Student';

class StudentController {
   async store(res, req) {
      const student = await Student.create(req.body);

      return res.json(student);
   }
}

export default new StudentController();

routes.js (Routes)

import { Router } from 'express';

import StudentController from './app/controllers/StudentController';

const routes = new Router();

routes.post('/students', StudentController.store);

export default routes;

And I'm using Insomnia to send data via POST. enter image description here

Any idea?

1

1 Answers

1
votes

I can think of two thing that go wrong here

1. StudentController.js

class StudentController {
   // Following should be `(req, res)`
   async store(res, req) { // <-- it should be (req, res) 
      const student = await Student.create(req.body);

      return res.json(student);
   }
}

2. App setting

As you didn't share the code for initiating express app like following

const express = require("express")
const app = express()

You may have missed to use the body parser middleware which parses the json body.