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:
Related
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,
},
);
I have a Server and User models and I've set a many-to-many relationship between them like this:
User.belongsToMany(Server, { through: 'Server_Users' });
Server.belongsToMany(User, { through: 'Server_Users' });
Then I get a user by his id, create a server and attempt to add the server to the user like this:
let user = await User.findByPk(userId)
let socketServer = await Server.create({
name: name,
thumbnail: thumbnail,
userId: userId
});
await user.addServer(socketServer)
This creates and inserts the server in the database, however, it doesn't create the relationship between the user and the server in the junction server_users table. I don't get any errors either so I've no clue what is going on.
The logging shows an INSERT for the server and then some sort of update:
Executing (default): SELECT `id`, `username`, `password`, `email`, `createdAt`, `updatedAt` FROM `users` AS `user` WHERE `user`.`id` = '1';
Executing (default): INSERT INTO `servers` (`id`,`userId`,`name`,`thumbnail`,`endpoint`,`rooms`,`createdAt`,`updatedAt`) VALUES (DEFAULT,?,?,?,?,?,?,?);
Executing (default): UPDATE `servers` SET `userId`=?,`updatedAt`=? WHERE `id` IN (25)
Try this one.
await user.addServer(Server, socketServer);
From documentation https://sequelize.org/master/class/lib/associations/belongs-to-many.js~BelongsToMany.html#instance-method-add
By the way, if you do it like this you will use 2 DB calls. You can reduce it to one by using .createServer method.
Please read it here: https://sequelize.org/master/class/lib/associations/belongs-to-many.js~BelongsToMany.html#instance-method-create
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
.
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.
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