1

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 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Here is a problem ( async store(res, req) { // <-- it should be (req, res) ). Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.