JS Sequelize Express Postgres API gives notNull Violation - node.js

Trying to learn sequelize, so I created a small test table and API. I am able to connect to the database and GET data from the API, but I can not insert anything. Sequelize is giving a warning that the value can't be null, even though I'm passing it in.
Call:
{payload=INSERT INTO api.testertab(submission_id, notes) VALUES (6452453223, 'testmessage2');, method=POST}
Basic Table Model:
const getTestertabModel = (sequelize, { DataTypes }) => {
const TT_ret = sequelize.define('testertab', {
submission_id: {
type: DataTypes.TEXT,
allowNull: false,
primaryKey: true
},
notes: {
type: DataTypes.TEXT,
allowNull: true
}
}, {
sequelize,
tableName: 'testertab',
schema: 'api',
timestamps: false,
indexes: [
{
name: "testertab_pkey",
unique: false,
fields: [
{ name: "submission_id" },
]
},
]
});
return TT_ret;
};
export default getTestertabModel;
and routes:
import { Router } from 'express';
const router = Router();
router.get('/', async (req, res) => {
console.log("get all")
const resp = await req.context.models.TT_ret.findAll()
return res.status(200).send(resp);
});
router.post('/upload', async (req, res) => {
console.log("post sub id")
//console.log(req.body)
const resp = await req.context.models.TT_ret.create();
return res.send(resp);
});
export default router;
index.js
import cors from 'cors';
import express from 'express';
import bodyParser from 'body-parser';
import models, { sequelize } from './src/models/index.js';
import routes from './src/routes/index.js';
const app = express();
import dotenv from 'dotenv/config';
app.use(bodyParser.json());
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use('/tab', routes.tester);
app.listen(process.env.port, () =>
console.log(`Example app listening on port ${process.env.port}!`),
);
Error message:
/root/node_modules/sequelize/lib/instance-validator.js:50
throw new sequelizeError.ValidationError(null, this.errors);
^
ValidationError [SequelizeValidationError]: notNull Violation: testertab.submission_id cannot be null
at InstanceValidator._validate (/root/node_modules/sequelize/lib/instance-validator.js:50:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async InstanceValidator._validateAndRunHooks (/root/node_modules/sequelize/lib/instance-validator.js:60:7)
at async InstanceValidator.validate (/root/node_modules/sequelize/lib/instance-validator.js:54:12)
at async model.save (/root/node_modules/sequelize/lib/model.js:2368:7)
at async Function.create (/root/node_modules/sequelize/lib/model.js:1344:12)
at async file:///root/easton_seqdb_api/src/routes/tester.js:14:16 {
errors: [
ValidationErrorItem {
message: 'testertab.submission_id cannot be null',
type: 'notNull Violation',
path: 'submission_id',
value: null,
origin: 'CORE',
instance: testertab {
dataValues: { submission_id: null },
_previousDataValues: {},
uniqno: 1,
_changed: Set(0) {},
_options: {
isNewRecord: true,
_schema: 'api',
_schemaDelimiter: '',
attributes: undefined,
include: undefined,
raw: undefined,
silent: undefined
},
isNewRecord: true
},
validatorKey: 'is_null',
validatorName: null,
validatorArgs: []
}
]
}

Related

joi validation is not working as i expected

I'm newbie to the nestjs here i wanna to do a joi validation ,if i hit the request
in my terminal it's showing the joi validation errors but not returning any joi error in the response
i have found that controller invoked even before joi middleware
here is my controller,validation and joi schema,
controller
#Post()
#UsePipes(new ValidationPipe(subReportSchema))
cardsteps(#Body() payload:createCardStepsDto):Promise<any>{
return this.cardStepservice.createCardSteps(payload);
}
joi schema
import * as Joi from 'joi';
export const subReportSchema = Joi.object({
stepId: Joi.string().optional(),
stepTitle: Joi.string().when('stepId', { is: 'null', then: Joi.required() }),
order: Joi.number().when('stepId', { is: 'null', then: Joi.required() }),
draft: Joi.boolean().when('stepId', { is: 'null', then: Joi.required() }),
time: Joi.string().when('stepId', { is: 'null', then: Joi.required() }),
date: Joi.string().when('stepId', { is: 'null', then: Joi.required() }),
cardId: Joi.string().when('stepId', { is: 'null', then: Joi.required() }),
counters: Joi.object({
attendees: Joi.number().optional(),
children: Joi.number().optional(),
adults: Joi.number().optional(),
boys: Joi.number().optional(),
girls: Joi.number().optional(),
over18: Joi.number().optional(),
under18: Joi.number().optional(),
over60: Joi.number().optional()
}).when('stepId', { is: 'null', then: Joi.required() }),
}).options({
abortEarly: false, allowUnknown: true
});
validation schema
import {
PipeTransform,
BadRequestException,
ArgumentMetadata,
} from '#nestjs/common';
import { ObjectSchema } from 'joi';
export class ValidationPipe implements PipeTransform {
constructor(private readonly schema: ObjectSchema) { }
transform(value: Record<string, any>) {
const { error } = this.schema.validate(value)
if (error) {
throw new BadRequestException({
error: "validation failed",
message: error.message.replace(/(\"|[\d])/g, ''),
});
}
return value;
}
}
output reflects in my terminal
ValidationError [SequelizeValidationError]: notNull Violation: cardStep.date cannot be null
at InstanceValidator._validate (/home/user-89/projects/report-back2/node_modules/sequelize/src/instance-validator.js:78:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at InstanceValidator._validateAndRunHooks (/home/user-89/projects/report-back2/node_modules/sequelize/src/instance-validator.js:111:7)
at InstanceValidator.validate (/home/user-89/projects/report-back2/node_modules/sequelize/src/instance-validator.js:93:12)
at cardStep.save (/home/user-89/projects/report-back2/node_modules/sequelize/src/model.js:3996:7)
at Function.create (/home/user-89/projects/report-back2/node_modules/sequelize/src/model.js:2280:12)
at CardStepService.createCardSteps (/home/user-89/projects/report-back2/src/card-step/card-step.service.ts:30:41)
at /home/user-89/projects/report-back2/node_modules/#nestjs/core/router/router-execution-context.js:46:28
at /home/user-89/projects/report-back2/node_modules/#nestjs/core/router/router-proxy.js:9:17 {
errors: [
ValidationErrorItem {
message: 'cardStep.date cannot be null',
type: 'notNull Violation',
path: 'date',
value: null,
origin: 'CORE',
instance: [cardStep],
validatorKey: 'is_null',
validatorName: null,
validatorArgs: []
}
]
}

Can't connect to Atlas cluster from my lambda using mongoose

I am trying to connect to a cluster using the last example from mongoose site
Here are my files using node14 and typescript
src/index.ts
import { APIGatewayProxyHandler } from "aws-lambda"
export { list as productsList } from "./products"
export const list: APIGatewayProxyHandler = (event, context, callback) => {
callback(null, {
statusCode: 200,
body: `Hello from ${process.env.AWS_SAM_BRANCH}`,
})
}
src/utils.ts
import mongoose from "mongoose"
import { APIGatewayProxyResult, Callback } from "aws-lambda"
let mongoConnection: Promise<typeof mongoose> | null = null
export const connectMongoose = async () => {
if (mongoConnection == null) {
const mongoURI = `mongodb+srv://USER:PASS#cluster0.ohjoj.mongodb.net/myFirstDB?retryWrites=true&w=majority`
mongoConnection = mongoose
.connect(mongoURI, { serverSelectionTimeoutMS: 3000 })
.then((mongooseReply) => {
console.log({ mongooseReply })
return mongoose
})
.catch((mongooseError) => {
console.log({ mongooseError })
return mongoose
})
await mongoConnection
}
return mongoConnection
}
export const errorHandler = (error: unknown, callback: Callback<APIGatewayProxyResult>) => {
console.error("catchedError", error)
if (error instanceof Error) {
callback(null, {
statusCode: 400,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ error: error.message }),
})
} else {
callback(null, {
statusCode: 500,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ error: "Internal server error" }),
})
}
}
src/products/index.ts
import { APIGatewayProxyHandler } from "aws-lambda"
import Model from "./model"
import { connectMongoose, errorHandler } from "../utils"
export const list: APIGatewayProxyHandler = (event, context, callback) => {
try {
connectMongoose()
Model.find({}, (error: unknown, reply: unknown) => {
if (error) throw error
callback(null, {
statusCode: 200,
headers: { "Content-Type": "application/json" },
body: JSON.stringify(reply),
})
})
} catch (error) {
errorHandler(error, callback)
}
}
src/products/model.ts
import mongoose from "mongoose"
const model = mongoose.model(
"Product",
new mongoose.Schema(
{
title: {
type: String,
required: true,
maxLength: 256,
},
description: {
type: String,
required: true,
maxLength: 2048,
},
count: {
type: Number,
required: true,
min: 0,
max: 1000 * 1000,
},
},
{
timestamps: true,
versionKey: false,
}
)
)
export default model
Here is the code in a repo is includes commands used to deploy with AWS SAM
https://github.com/LuisEnMarroquin/aws-sam-mongo
There are 2 routes in my app
https://2us58gl430.execute-api.us-east-2.amazonaws.com/
This works and returns Hello from test with status 200
https://2us58gl430.execute-api.us-east-2.amazonaws.com/products
This doesn't work and returns {"message":"Internal Server Error"} with status 500
Here are the CloudWatch logs exported as CSV
timestamp,message
1647203544609,"START RequestId: 83fd3fc8-1134-4ff4-a5f7-7e83a65159ce Version: $LATEST
"
1647203545742,"2022-03-13T20:32:25.685Z 83fd3fc8-1134-4ff4-a5f7-7e83a65159ce INFO {
mongooseReply: <ref *1> Mongoose {
connections: [ [NativeConnection] ],
models: { Product: Model { Product } },
events: EventEmitter {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
[Symbol(kCapture)]: false
},
options: {
pluralization: true,
autoIndex: true,
autoCreate: true,
[Symbol(mongoose:default)]: true
},
_pluralize: [Function: pluralize],
Schema: [Function: Schema] {
reserved: [Object: null prototype],
Types: [Object],
ObjectId: [Function]
},
model: [Function (anonymous)],
plugins: [ [Array], [Array], [Array], [Array], [Array], [Array] ],
default: [Circular *1],
mongoose: [Circular *1]
}
}
"
1647203549616,"END RequestId: 83fd3fc8-1134-4ff4-a5f7-7e83a65159ce
"
1647203549616,"REPORT RequestId: 83fd3fc8-1134-4ff4-a5f7-7e83a65159ce Duration: 5005.75 ms Billed Duration: 5000 ms Memory Size: 128 MB Max Memory Used: 76 MB Init Duration: 366.30 ms
"
1647203549616,"2022-03-13T20:32:29.616Z 83fd3fc8-1134-4ff4-a5f7-7e83a65159ce Task timed out after 5.01 seconds
"
As explained in this GitHub issue
A few suggestions:
You should either choose between a full callback approach and a full promise approach
Don't mix async / await with .then syntax when you can avoid it
import mongoose from "mongoose"
import { APIGatewayProxyHandler } from "aws-lambda"
let mongoConnection: Promise<typeof mongoose> | null = null
const connectMongoose = async () => {
if (mongoConnection == null) {
const mongoURI = `mongodb+srv://YOUR_CLUSTER_URL`
mongoConnection = mongoose
.connect(mongoURI, { serverSelectionTimeoutMS: 3000 })
.then((mongooseReply) => {
console.log({ mongooseReply })
return mongoose
})
.catch((mongooseError) => {
console.log({ mongooseError })
return mongoose
})
await mongoConnection
}
return mongoConnection
}
const Model = mongoose.model(
"Product",
new mongoose.Schema(
{
title: String,
description: String,
},
{
timestamps: true,
versionKey: false,
}
)
)
export const myRoute: APIGatewayProxyHandler = async (event, context) => {
try {
await connectMongoose();
const reply = await Model.find({}).exec();
return {
statusCode: 200,
headers: { "Content-Type": "application/json" },
body: JSON.stringify(reply),
};
} catch (error) {
return {
statusCode: 400,
headers: { "Content-Type": "application/json" },
body: "Server error",
};
}
}

server doesn't send response for Sequelize many to many relationship query

I am new to sequelize and node js. I have been trying to implement Sequelize Many-to-Many Association using node.js, express with PostgreSQL database following this tutorial. I have implemented a single table and retrieve data correctly without any issue. But in many-to-many relationships, I can only print data to console and in postman and chrome, it keeps loading around a minute and wait without loading data. Here are my code files.
db config file
const dbConfig = require("../config/db.config.js");
const Sequelize = require("sequelize");
const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
host: dbConfig.HOST,
dialect: dbConfig.dialect,
operatorsAliases: false,
define: {
timestamps: true,
freezeTableName: true
},
pool: {
max: dbConfig.pool.max,
min: dbConfig.pool.min,
acquire: dbConfig.pool.acquire,
idle: dbConfig.pool.idle
}
});
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
db.actor = require("./actor.model.js")(sequelize, Sequelize);
db.film = require("./film.model.js")(sequelize, Sequelize);
db.film_actor = require("./film_actor.model.js")(sequelize, Sequelize);
db.film.belongsToMany(db.actor, {
through: db.film_actor,
as: "actors",
foreignKey: "film_id",
});
db.actor.belongsToMany(db.film, {
through: db.film_actor,
as: "films",
foreignKey: "actor_id",
});
module.exports = db;
filmController file
const db = require("../models");
const Film = db.film;
const Actor = db.actor;
//find all films including actors
exports.findAll = () => {
return Film.findAll({
include: [
{
model: Actor,
as: "actors",
attributes: ["first_name", "last_name"],
through: {
attributes: [],
}
},
],
})
.then((film) => {
console.log(film[5]);
return film;
})
.catch((err) => {
console.log(">> Error while retrieving films: ", err);
});
};
// find film by film id
exports.findById = (req, res) => {
const film_id = req.params.id;
return Film.findByPk(film_id, {
include: [
{
model: Actor,
as: "actors",
attributes: ["first_name", "last_name"],
through: {
attributes: [],
}
},
],
})
.then((films) => {
return films;
})
.catch((err) => {
console.log(">> Error while finding film: ", err);
});
};
film.route file
module.exports = app => {
const film = require("../controllers/film.controller.js");
var router = require("express").Router();
// Retrieve all films
router.get("/films", film.findAll);
// Retrieve a single actor with id
router.get("/films/:id", film.findById);
app.use('/api', router);
};
server.js file
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const filmController = require("./app/controllers/film.controller");
const app = express();
const db = require("./app/models");
db.sequelize.sync();
var corsOptions = {
origin: "http://localhost:8081"
};
app.use(cors(corsOptions));
// parse requests of content-type - application/json
app.use(express.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
// simple route
app.get("/", (req, res) => {
res.json({ message: "Welcome to bezkoder application." });
});
db.sequelize.sync().then(() => {
// run();
});
require("./app/routes/actor.routes")(app);
require("./app/routes/film.routes")(app);
// app.get('/films',filmController.findAll);
// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
As per my understanding, the issue should be about the routing. I created route for many to many associations as the same way I did for singe table(actor) but this problem occurred. I put a console log under findAll() method in filCcontroller and it prints the data in the console along with the query.
This is the output on my console
Executing (default): SELECT "film"."film_id", "film"."title", "film"."description", "film"."release_year", "film"."language_id", "film"."rental_duration", "film"."length", "actors"."actor_id" AS "actors.actor_id", "actors"."first_name" AS "actors.first_name", "actors"."last_name" AS "actors.last_name" FROM "film" AS "film" LEFT OUTER JOIN ( "film_actor" AS "actors->film_actor" INNER JOIN "actor" AS "actors" ON
"actors"."actor_id" = "actors->film_actor"."actor_id") ON "film"."film_id" = "actors->film_actor"."film_id";
film {
dataValues: {
film_id: 166,
title: 'Color Philadelphia',
description: 'A Thoughtful Panorama of a Car And a Crocodile who must Sink a Monkey in The Sahara Desert',
release_year: 2006,
language_id: 1,
rental_duration: 6,
length: 149,
actors: [
[actor], [actor],
[actor], [actor],
[actor], [actor],
[actor]
]
},
_previousDataValues: {
film_id: 166,
title: 'Color Philadelphia',
description: 'A Thoughtful Panorama of a Car And a Crocodile who must Sink a Monkey in The Sahara Desert',
release_year: 2006,
language_id: 1,
rental_duration: 6,
length: 149,
actors: [
[actor], [actor],
[actor], [actor],
[actor], [actor],
[actor]
]
},
_changed: Set {},
_options: {
isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
include: [ [Object] ],
includeNames: [ 'actors' ],
includeMap: { actors: [Object] },
includeValidated: true,
attributes: [
'film_id',
'title',
'description',
'release_year',
'language_id',
'rental_duration',
'length'
],
raw: true
},
isNewRecord: false,
actors: [
actor {
dataValues: [Object],
_previousDataValues: [Object],
_changed: Set {},
_options: [Object],
isNewRecord: false
},
actor {
dataValues: [Object],
_previousDataValues: [Object],
_changed: Set {},
_options: [Object],
isNewRecord: false
},
actor {
dataValues: [Object],
_previousDataValues: [Object],
_changed: Set {},
_options: [Object],
isNewRecord: false
},
actor {
dataValues: [Object],
_previousDataValues: [Object],
_changed: Set {},
_options: [Object],
isNewRecord: false
},
actor {
dataValues: [Object],
_previousDataValues: [Object],
_changed: Set {},
_options: [Object],
isNewRecord: false
},
actor {
dataValues: [Object],
_previousDataValues: [Object],
_changed: Set {},
_options: [Object],
isNewRecord: false
},
actor {
dataValues: [Object],
_previousDataValues: [Object],
_changed: Set {},
_options: [Object],
isNewRecord: false
}
]
}
any help would be greatly appreciated.

Trouble connecting express api to nuxt app and mongodb

It's been seriously 10 days since i'm trying to deploy my web app online. i've gone back and forth between heroku and digital ocean. nothing solved. i've asked questions here all i get is a long post with technical terms i' not able to understand. Here's my problem :
i have a nuxt app with express.js in the backend and mongodb as the database. At first i had trouble with configuring host and port for my nuxt app. once i fixed it, anoither problem appeared : i'm not receiving data from the database. i don't if it's something related to database connection or with the express api configuration.
here's my nuxt config
export default {
ssr: false,
head: {
titleTemplate: 'Lokazz',
title: 'Lokazz',
meta: [
{ charset: 'utf-8' },
{
name: 'viewport',
content: 'width=device-width, initial-scale=1'
},
{
hid: 'description',
name: 'description',
content:
'Lokazz'
}
],
link: [
{
rel: 'stylesheet',
href:
'https://fonts.googleapis.com/css?family=Work+Sans:300,400,500,600,700&amp;subset=latin-ext'
}
]
},
css: [
'swiper/dist/css/swiper.css',
'~/static/fonts/Linearicons/Font/demo-files/demo.css',
'~/static/fonts/font-awesome/css/font-awesome.css',
'~/static/css/bootstrap.min.css',
'~/assets/scss/style.scss'
],
plugins: [
{ src: '~plugins/vueliate.js', ssr: false },
{ src: '~/plugins/swiper-plugin.js', ssr: false },
{ src: '~/plugins/vue-notification.js', ssr: false },
{ src: '~/plugins/axios.js'},
{ src: '~/plugins/lazyLoad.js', ssr: false },
{ src: '~/plugins/mask.js', ssr: false },
{ src: '~/plugins/toastr.js', ssr: false },
],
buildModules: [
'#nuxtjs/vuetify',
'#nuxtjs/style-resources',
'cookie-universal-nuxt'
],
styleResources: {
scss: './assets/scss/env.scss'
},
modules: ['#nuxtjs/axios', 'nuxt-i18n','vue-sweetalert2/nuxt', '#nuxtjs/auth-next', "bootstrap-vue/nuxt"],
bootstrapVue: {
bootstrapCSS: false, // here you can disable automatic bootstrapCSS in case you are loading it yourself using sass
bootstrapVueCSS: false, // CSS that is specific to bootstrapVue components can also be disabled. That way you won't load css for modules that you don't use
},
i18n: {
locales: [
{ code: 'en', file: 'en.json' },
],
strategy: 'no_prefix',
fallbackLocale: 'en',
lazy: true,
defaultLocale: 'en',
langDir: 'lang/locales/'
},
router: {
linkActiveClass: '',
linkExactActiveClass: 'active',
},
server: {
port: 8080, // default: 3000
host: '0.0.0.0' // default: localhost
},
auth: {
strategies: {
local: {
token: {
property: "token",
global: true,
},
redirect: {
"login": "/account/login",
"logout": "/",
"home": "/page/ajouter-produit",
"callback": false
},
endpoints: {
login: { url: "/login", method: "post" },
logout: false, // we don't have an endpoint for our logout in our API and we just remove the token from localstorage
user:false
}
}
}
},
};
here's my package.json
{
"name": "martfury_vue",
"version": "1.3.0",
"description": "Martfury - Multi-purpose Ecomerce template with vuejs",
"author": "nouthemes",
"private": true,
"scripts": {
"dev": "nuxt",
"build": "nuxt build",
"start": "nuxt start",
"generate": "nuxt generate"
},
"config": {
"nuxt": {
"host": "0.0.0.0",
"port": "8080"
}
},
}
here's my repository.js file
import Cookies from 'js-cookie';
import axios from 'axios';
const token = Cookies.get('id_token');
const baseDomain = 'https://lokazzfullapp-8t7ec.ondigitalocean.app';
export const customHeaders = {
'Content-Type': 'application/json',
Accept: 'application/json'
};
export const baseUrl = `${baseDomain}`;
export default axios.create({
baseUrl,
headers: customHeaders
});
export const serializeQuery = query => {
return Object.keys(query)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(query[key])}`)
.join('&');
};
an example of an api call i make locally that works without a problem :
import Repository, { serializeQuery } from '~/repositories/Repository.js';
import { baseUrl } from '~/repositories/Repository';
import axios from 'axios'
const url = baseUrl;
export const actions = {
async getProducts({ commit }, payload) {
const reponse = await axios.get(url)
.then(response => {
commit('setProducts', response.data);
return response.data;
})
.catch(error => ({ error: JSON.stringify(error) }));
return reponse;
},
}
here's my index.js (express file)
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose')
const cors = require('cors');
//const url = 'mongodb://localhost:27017/lokazz'
const url = 'mongodb+srv://lokazz:zaki123456#cluster0.hsd8d.mongodb.net/lokazz?retryWrites=true&w=majority'
const jwt = require('jsonwebtoken')
const con = mongoose.connection
mongoose.connect(url, {useNewUrlParser:true}).then(()=>{
const app = express();
// middlleware
app.use(express.json())
app.use(cors());
//products routes
const products = require('./product/product.router');
app.use('/', products)
//users routes
const users = require('./user/user.router');
app.use('/', users)
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
}).catch(error => console.log(error.reason));
con.on('open', () => {
console.log('connected...')
})
My directory structure
the error i get after the api request, meaning it's not receving any data.
ebd1ecd.js:2 TypeError: Cannot read properties of undefined (reading 'username')
at f.<anonymous> (c88240c.js:1)
at f.t._render (ebd1ecd.js:2)
at f.r (ebd1ecd.js:2)
at wn.get (ebd1ecd.js:2)
at new wn (ebd1ecd.js:2)
at t (ebd1ecd.js:2)
at f.In.$mount (ebd1ecd.js:2)
at init (ebd1ecd.js:2)
at ebd1ecd.js:2
at v (ebd1ecd.js:2)
idk if it's a problem with mongodb connection cluster or the api call.

SequelizeDatabaseError UPDATE using PostgreSQL

I have 5 endpoint with 4 methods implemented. For GET, POST, DELETE all of them goes well. I don't understand why PUT method doesn't work. In my case, I need to update column first_name and last_name but it send me error like this:
{
"name": "SequelizeDatabaseError",
"parent": {
"length": 221,
"name": "error",
"severity": "ERROR",
"code": "42703",
"where": "PL/pgSQL function last_updated() line 3 at assignment",
"file": "d:\\pginstaller_13.auto\\postgres.windows-x64\\src\\pl\\plpgsql\\src\\pl_exec.c",
"line": "5170",
"routine": "exec_assign_value",
"sql": "UPDATE \"actors\" SET \"first_name\"=$1,\"last_name\"=$2,\"updatedAt\"=$3 WHERE \"actor_id\" = $4",
"parameters": [
"Anne ",
"Anne",
"2020-10-29 02:54:11.642 +00:00",
"200"
]
},
"original": {
"length": 221,
"name": "error",
"severity": "ERROR",
"code": "42703",
"where": "PL/pgSQL function last_updated() line 3 at assignment",
"file": "d:\\pginstaller_13.auto\\postgres.windows-x64\\src\\pl\\plpgsql\\src\\pl_exec.c",
"line": "5170",
"routine": "exec_assign_value",
"sql": "UPDATE \"actors\" SET \"first_name\"=$1,\"last_name\"=$2,\"updatedAt\"=$3 WHERE \"actor_id\" = $4",
"parameters": [
"Anne ",
"Anne",
"2020-10-29 02:54:11.642 +00:00",
"200"
]
},
"sql": "UPDATE \"actors\" SET \"first_name\"=$1,\"last_name\"=$2,\"updatedAt\"=$3 WHERE \"actor_id\" = $4",
"parameters": [
"Anne ",
"Anne",
"2020-10-29 02:54:11.642 +00:00",
"200"
]
}
This is how i tested in Postman
And this is my models:
const actor = (sequelize, DataTypes) => {
const Actor = sequelize.define('actor', {
actor_id: {
type: DataTypes.INTEGER,
primaryKey: true,
unique: true,
autoIncrement: true,
allowNull: false,
},
first_name: {
type: DataTypes.STRING(45),
allowNull: false,
},
last_name: {
type: DataTypes.STRING(45),
allowNull: false,
},
createdAt: {
type: DataTypes.DATE,
},
updatedAt: {
type: DataTypes.DATE,
},
});
return Actor;
};
export default actor;
Help me, please. I have searched all around for the answer but still stuck.
UPDATE:
Here is my code when instantiate Sequelize:
import Sequelize from 'sequelize';
const sequelize = new Sequelize(
process.env.DATABASE,
process.env.DATABASE_USER,
process.env.DATABASE_PASSWORD,
{
dialect: 'postgres',
},
);
const models = {
Actor: sequelize.import('./actor'),
};
export { sequelize };
export default models;
And this is my app.js:
import 'dotenv/config';
import cors from 'cors';
import express from 'express';
import path from 'path';
import models, { sequelize } from './models';
import routes from './routes';
const app = express();
// Application-Level Middleware
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(async (req, res, next) => {
req.context = {
models,
me: await models.Actor,
};
next();
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(express.static(path.join(__dirname, 'public')));
// Routes
app.get('/', async (req, res) => {
try {
res.render('index');
} catch (error) {
res.send(error);
}
});
app.use('/actor', routes.actor);
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
// Start
sequelize.sync().then(async () => {
app.listen(process.env.PORT, () =>
console.log(`App listening on port ${process.env.PORT}!`),
);
});
module.exports = app;
Also, this is my actual table structure
[SOLVED]
This happen because I have deleted one column named "last_updated" that used as trigger when UPDATE, image . Now I disable that trigger and can successfully update.
My mistake, this DB I import from here and didn't give attention to it

Resources