Sequelize: Unknown column *.createdAt in 'field list' - javascript

I've come across this problem several times in the past and have read a number of solutions. Before I go through them again, I was hoping someone could explain exactly what the problem is - because despite eventually fixing it, I never really understand why
The error:
original: Error: Unknown column 'job.createdAt' in 'field list'
What I assume is the source (as I just added it):
[Sequelize.fn('date_format', Sequelize.col('job.createdAt' ), '%d/%m/%y'), 'jobDate']
The error suggests that createdAt isn't a column in the jobs table - several solutions suggest defining createdAt in your model (which I'd already done).
What also confuses me is that in workbench I can run the query:
SELECT * FROM test.jobs ORDER BY test.jobs.createdAt;
and it works, and that I don't have this problem with the equivalent Company attribute.
Job Model:
const Job = sequelize.define('job', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
},
title: {
type: Sequelize.STRING,
allowNull: false
},
...
createdAt: {
type: Sequelize.DATE(3),
allowNull: false,
},
updatedAt: {
type: Sequelize.DATE(3),
allowNull: false,
}
});
The options object for the query:
const options = {
include: [
{
model: Job,
attributes: [
'id',
'title',
// ...
'createdAt',
[Sequelize.fn('date_format', Sequelize.col('job.createdAt' ), '%d/%m/%y'), 'jobDate'],
]
},
],
attributes: [
'id',
'name',
'createdAt',
[Sequelize.fn('date_format', Sequelize.col('company.createdAt' ), '%d/%m/%y'), 'companyDate'],
],
order: [[ orderField, orderDirection ]],
distinct: true
}
Workbench showing the column:
As far as I can tell the relevant part(?) of the actual sql query looks right too
`jobs`.`createdAt` AS `jobs.createdAt`, date_format(`job`.`createdAt`, '%d/%m/%y') AS `jobs.jobDate`,
Appreciate any help

Related

Sequelize model with column using references ignores field option

I am not sure if this is a bug or issue with me, but I have this basic model
const { DataTypes } = require('sequelize');
sequelize.define(
'Submission',
{
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER,
},
widgetId: {
allowNull: false,
type: DataTypes.INTEGER,
references: {
field: 'widget_id',
model: {
tableName: 'widget',
schema: 'public',
},
key: 'id',
},
field: 'widget_id',
},
createdAt: {
type: DataTypes.DATE,
field: 'created_at',
},
updatedAt: {
type: DataTypes.DATE,
field: 'updated_at',
},
},
{
tableName: 'submission',
timestamps: true,
underscored: true,
},
);
and the widget model is identical except the columns/fields and has a id field. I am able to create a widget object / row in our db perfectly fine.
When trying to expand that and create a submission entry at same time as the widget, i expanded things and testing it out by adding the associations and test code as such
widget.submission = widget.hasOne(submission);
submission.widget = submission.belongsTo(widget);
instance.models.Widget.create({
widgetId: '123456789',
title: 'test',
Submission: {
message: 'test',
},
}, {
include: [{
association: widget.submission,
}]
}).then(r => console.log(r))
.catch(err => console.log(err));
and I get the following error
ValidationError [SequelizeValidationError]: notNull Violation: Submission.widgetId cannot be null
it seems to ignore my field: 'widget_id and assumes widgetId. The field option seems to work for everything else but this
anyway to handle that? thank you!

returning extra column with formatted date

I have a schema(table) like following in seqluelize:
const schema = sequelize.define("order_entry_header", {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
date: {
type: DataTypes.TEXT,
},
sub_total: {
type: DataTypes.DOUBLE,
},
...
});
My requirement is whenever I call or use or include this schema order_entry_header in
any place in my app I want date column in to format in a readable text in a different column called date_format
In simple sql this should be something like below:
SELECT
id,
date,
DATE_FORMAT(date, "%d/%m/%Y") as date_format
...
FROM order_entry_header;
I am joining/fetching this table data in numerous places and every-time I have to add extra column to get the formatted date specifically. I want this to be automated.
.
.
With instanceMethod it can be performed. but I have to call the method every-time I get the data which is a little confusing sometimes.
.
.
Is there any ways to do so?
You can try to use Default scope (see Scopes)
const schema = sequelize.define("order_entry_header", {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
date: {
type: DataTypes.TEXT,
},
sub_total: {
type: DataTypes.DOUBLE,
},
...
}, {
defaultScope: {
attributes: [{ include: [[Sequelize.fn('DATE_FORMAT', Sequelize.col('date')), 'date_format']]}]
active: true
}
}
});

Sequelize asking for multiple values of association when explicitly defining foreign key

I am creating a model in sequelize as:
const Desk = sequelize.define('Desk', {
id: {
type: DataTypes.BIGINT,
allowNull: false,
primaryKey: true,
autoIncrement: true,
},
number: {
type: DataTypes.INTEGER,
allowNull: false,
},
},
{
indexes: [
{
unique: true,
fields: ['store_id', 'number'],
message: 'A desk with same number exists on this store'
}
],
tableName: 'desk',
underscored: true,
});
I create an association as such:
Desk.belongsTo(models.Store, {
foreignKey: {
name: 'storeId',
allowNull: false
}
});
I explicitly specify the name of the foreign key so that I can add it as an index.
The problem arises when I try to create a row as such:
const data = { number: 4, storeId: 1 };
await Desk.create(data);
The above code raises an exception that StoreId cannot be null even though I explicitly changed the foreign key to storeId. Even if I try changing the data to
const data = { number: 4, StoreId: 1 };
I get the error: storeId cannot be null
I don't understand if I making some mistake in creating the model but it should not be asking me for multiple values of same field.

SequelizeDatabaseError: operator does not exist uuid = integer

I'm trying to make a join with two tables based on UUID (I have id too), those tables have some difficult relations...
When I run the query I get the error.
The first table is called users, and his UUID is called registry_uuid.
The second table beneficiaries but this table has two UUID, uuid_beneficiary and uuid_benefactor.
Why? because the first table has a column user_type_id and with this we can know if it's a user beneficiary or benefactor.
And the second table is to know which users are related.
Model Users:
const User = sequelize.define('users', {
registry_uuid: {
type: Sequelize.UUIDV4,
defaultValue: Sequelize.UUIDV4,
allowNull: false
},
user_type_id: {
type: Sequelize.INTEGER,
defaultValue: 1,
allowNull: false
}
}
Model Beneficiaries:
const Beneficiary = sequelize.define('beneficiaries', {
uuid_benefactor: {
type: Sequelize.UUIDV4,
defaultValue: Sequelize.UUIDV4,
allowNull: false
},
uuid_beneficiary: {
type: Sequelize.STRING,
defaultValue: Sequelize.UUIDV4,
allowNull: false
},
created_at: {
type: Sequelize.DATE,
defaultValue: Sequelize.NOW
},
disassociation_date: {
type: Sequelize.DATE,
defaultValue: null
}
}
Query:
async function getBenefactorOfBeneficiary (benefactorUuid, arrayAttributes) {
arrayAttributes = arrayAttributes || ['registry_uuid', 'name', 'last_name', 'picture']
return UserModel.findOne({
where: {
registry_uuid: {
[Op.eq]: benefactorUuid
}
},
include: [{
model: BeneficiaryModel,
}],
attributes: arrayAttributes,
raw: true
})
}
Relation:
UserModel.hasMany(beneficiaryModel, {foreignKey: 'uuid_benefactor'})
beneficiaryModel.belongsTo(UserModel, {foreignKey: 'registry_uuid'})
I expect the output:
Example:
{
"name": "string",
"lastName": "string",
"picture": "string",
"created_at" "string"
}
obviously I modify the response in controller
You should first check the models that you are including and their ID types. They must have same type. Beside that, let's say we have User and Role models. Every User can have only one role and a Role can be used by several Users. In this case, you will get this error if you write the associations wrong.
Wrong version:
// Under the user model associations
user.hasOne(models.role, { foreignKey: "roleId" });
// this will try to compare your userId with roleId of Role table
// Under the Role model associations
role.hasMany(models.user, { foreignKey: "roleId" });
Right version should be like:
// Under the user model associations
user.hasOne(models.role, { foreignKey: "roleId" });
// this will try to compare your roleId from User model with roleId of Role table
// Under the Role model associations
role.hasMany(models.user, { foreignKey: "roleId" });
If you need more details, read https://sequelize.org/master/manual/assocs.html

Can't add new attributes to existing model sails.js

I'm quite newbie in sails.js. I need to add fields to an existing model in sails js.
Here it is
module.exports = {
attributes: {
id: {
columnName: 'id',
type: 'integer',
autoIncrement: true,
primaryKey: true,
unique: true
},
username: {
columnName: 'username',
type: 'STRING',
required: true,
},
userLevel: {
columnName: 'user_level',
type: 'integer',
required: true,
defaultsTo: 1
},
...
But as soon as I add the fields in my model js like
newAttribute: {
columnName: 'new_attribute',
type: 'integer',
required: true
}
I get an error "E_UKNOWN".
To be more precise, when I try to login with updated model, I get this message:
rr {"data":{"err":{"error":"E_UNKNOWN","status":500,"summary":"Encountered an unexpected error","raw":{"code":"ER_BAD_FIELD_ERROR","errno":1054,"sqlState":"42S22","index":0}}},"status":401,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"data":{*email and password here*},"url":"auth/login","headers":{"Accept":"application/json, text/plain, */*","Content-Type":"application/json;charset=utf-8"}},"statusText":"Unauthorized"}
Appreciate your help.
UPD It's working if I set NODE_ENV to development. May it could be the problem with connection.js file?
Seems that I've found the solution of my problem. At first I set NODE_ENV to development, and, I guess, the tables were created. Then I change NODE_ENV to production. And now it's working without odd errors.

Categories

Resources