Fetch data from Table using sequelizejs in Node.js - node.js

I am new in node.js, i want to fetch the data from table of the postgresql using sequelize ORM in node.js. I am using below code but its not working.
const apisListModel = sequelize.define('apisList', {});
apisListModel.findAll().then((data)=>{
JSON.stringify(data,undefined,2);
},(e)=>{
console.log(e);
});
Its give me error
Executing (default): SELECT "id", "createdAt", "updatedAt" FROM
"apisLists" AS "apisList";
{ SequelizeDatabaseError: relation "apisLists" does not exist
But apiList table exist in my DATABASE

Sequelize changes the tableName to plural implicitly. You can define options as
const apisListModel = sequelize.define('apisList', {}, {
tableName: 'apisList'
})

The query trying to fetch data from apisLists but your table name is apiList. Note the "s" in table name.
If this is the case, you can specify the table name using the option
tableName: 'apiList'
Here is the Documentation link

Related

How to fix Sequelize auto + character "s" in model

I define models with Sequelize and Nodejs but key i define is:
var User = fsdb.define("user", {...})
and in my database I was create table have name the same: "user"
but when run sequelize run sql is:
'SELECT `id`, `username`, `password`, `email`, `createdAt`, `updatedAt` FROM `users` AS `user`;'
so this show error
original: Error: Table 'sql6587389.users' doesn't exist
how to fix it
Thanks for any support
You can use the freezeTableName option when defining your model. In your case it would look like this:
const User = fsdb.define("user", {...}, { freezeTableName: true });
From the linked documentation:
You can stop the auto-pluralization performed by Sequelize using the freezeTableName: true option. This way, Sequelize will infer the table name to be equal to the model name, without any modifications:

Sequelize table name updates

I have a table in Postgres and for ORM I am using sequelize I need to update the table name so I've tried the below migration for this
queryInterface.renameTable('table1', 'table2', { transaction }
but for some reason, it's creating a new table with table2 with the same data as table 1 but table 1 still exits with blank data.is this correct behavior of this function so'll add a delete query.
This works
queryInterface.renameTable('OldTableName', 'NewTableName');
For that use case i normally rely on raw queries:
const { sequelize } = queryInterface;
await sequelize.query(
`ALTER TABLE table1
RENAME TO table2`,
{
type: QueryTypes.RAW,
raw: true,
transaction,
},
);

How to write setval() in TypeORM in NestJS?

I am using TypeORM and PostgreSQL in NestJS and I am facing a problem called error: duplicate key value violates unique constraint "message_pkey". I have searched and found out it's a common problem in PostgreSQL, but to solve this problem, I have to write this query:
SELECT setval('TABLENAME_id_seq', (SELECT MAX(id) FROM "TABLENAME"));
// Change TABLENAME with your table
But I can't find how to write this in TypeORM or query builder in NestJS?
Maybe a raw SQL query is a possible solution:
import { getManager } from 'typeorm';
const table = 'tablename';
await getManager().query(`SELECT setval('${table}_id_seq', (SELECT MAX(id) FROM "${table}"))`);

When updating Sequelize model, fails and returns different table name than I provided?

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);
});
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
.

Sequelize - Update table that has trigger on it - not working

I am kinda of new with Sequelize and Node.js
I am trying to use Sequelize with a MSSQL database and figure out what i can do with it.
I've established the connection, created a model based on a existing table.
Such table has multiple triggers on it.
When i try to execute something like this
sampletable.update({
NAME: "TEST"
},
{
where: {ID: 0},
silent: true
},
).then(function(result){
console.log(result);
})
where "sampletable" is an imported model
var sampletable = sequelize.import('./models/sampletable.js');
that was created with with "SequelizeAuto" (based on existing table's structure)
var SequelizeAuto = require('sequelize-auto')
var auto = new SequelizeAuto(config.database, config.username, config.password, config);
auto.run(function (err) {
if (err) throw err;
});
i get following error
"Unhandled rejection SequelizeDatabaseError: The target table 'sampletable' of the DML statement cannot have any enabled triggers if the statement contains an OUTPUT clause without INTO clause."
Statement executed
Executing (default): UPDATE [sampletable] SET [NAME]=N'test' OUTPUT INSERTED.* WHERE [id] = 0
Is it possible to update table with triggers with sequelize??
If yes, can anybody point me in the right direction??
I've googled, checked doco, but i can;t find much about it.
TIA
Try adding hasTrigger: true to your model options. This prevents Tedious from trying to output the results from the base table, and uses a temp table instead.

Resources