1

I'm running PostgreSQL 11, and attempting to update one of its table entries using Sequelize.

My NodeJS code:

require('env2')('.env');
const Sequelize = require('sequelize');

const sequelize=new Sequelize(process.env.database,process.env.username,process.env.password,{
    dialect:'postgres'
});

const Agent=sequelize.define('agent');
updateValues={available:false};
Agent.update(updateValues,{where:{phonenumber:'+18005551212'}}).then(result=>{console.log(result)});

The table agent has the structure:

id primary key serial,
phonenumber varchar(100),
available boolean

When I run the NodeJS code, I get this error:

Executing (default): UPDATE "agents" SET "updatedAt"='2018-12-27 10:16:54.504 +0
0:00' WHERE "phonenumber" = '+18005551212'
Unhandled rejection SequelizeDatabaseError: relation "agents" does not exist

Why is this update failing? I don't understand why the error is talking about the relation "agents", when I provided the table name as "agent" in sequelize.define(agent).

The update is successful when I use raw SQL as follows:

sequelize.query("update agent set available=false where phonenumber='+18005551212'").then(result=>{
    console.log(result);
});
sigil
  • 9,370
  • 40
  • 119
  • 199

1 Answers1

1

By default sequelize creates a table with a plural of its definition name, so when you do sequelize.define('agent') it actually creates a table with name agents . If you don't want to change your table name naturally you can use freezeTableName: true option in sequelize definition. More can be found in this answer. Refer Sequelize configuration doc .

  • That works, though with the call `sequelize.define('agent',{},{freezeTableName:true,tableName: 'agent'});` I'm now getting an error `column "updatedAt" of relation "agent" does not exist`. – sigil Dec 28 '18 at 21:10
  • Is that you created your table yourself or you ran generate and migration command? It may occur if migration wasn't done properly. More can be found in Sequelize cli documents – Harsh Vishwakarma Dec 31 '18 at 10:06
  • I created the table myself. I haven't run any generate and migration command. – sigil Jan 02 '19 at 20:24
  • updatedAt, createdAt are additional columns created when you run sequelize generate and migration, in addition to that it creates an additional table in your current database which stores meta data. Now that you have created table by yourself it may not have these columns which it tries to fetch orelse update by default. I'll suggest you to create tables with generate and migrate command for smoother implementation. – Harsh Vishwakarma Jan 02 '19 at 20:31