Configure TypeORM default foreign key to follow underscore format instead of camelCase - nestjs

Is there a way so all foreign key generated follows underscore user_id instead of camelCase userId.
Is there a way to configure TypeORM so I don't have to think about it when define the relation.
`userId` varchar(36) COLLATE utf8mb4_unicode_ci DEFAULT NULL

Yes this is possible by specifiying name property when you define your column like such (see all possible options here https://typeorm.io/#/entities/column-options):
#Column('int', { 'name': 'user_id' })
userId: number
The database field will then be user_id but when accessing the entity it will be mapped back to userId

Related

Creating entity relationship using a jdl in jhipster

I have the below JDL that I am using to create the jhipster application.
entity AuthClient(auth_client) {
msisdn String required maxlength(255),
email String required unique maxlength(255),
password String required maxlength(255),
lastLogin Instant,
createdAt Instant required,
createdBy Integer,
updatedAt Instant,
updatedBy Integer,
isDeleted Boolean required,
deletedAt Instant,
deletedBy Integer
}
entity AuthToken(auth_token) {
token String required maxlength(255),
appId Integer required,
appVersionName String maxlength(255),
clientId Integer required,
}
entity ClientProfile(client_profile) {
fName String required maxlength(255),
mName String maxlength(255),
lName String required maxlength(255),
gender Integer,
clientId Integer required
}
// Relations
relationship OneToMany {
AuthClient{AuthToken(clientId)} to AuthToken{AuthClient}
}
relationship OneToOne{
ClientProfile{AuthClient} to AuthClient{ClientProfile(clientId)},
}
// Options
service * with serviceClass
paginate * with pagination
dto * with mapstruct
filter *
However, instead of using the variable clientId as the foreign key it creates another field in the database.
I need to use the clientId as the foreign key in this application and not the generated new field Auth Client
Defining a clientId field as you did has no impact on the relationship, these are two separate things.
When you define a relationship, a field is automatically created in the entity and its type is of the related class: it's a reference to an object in the java entity and a foreign key column in the database table.
By default, the foreign key column will be named as auth_client_id and the field will be named as authClient. However, the JDL syntax for relationships lets you configure the relationship name and so modify the generated names.
So, remove all the clientId fields and modify your relationships definitions as follows:
// Relations
relationship OneToMany {
AuthClient to AuthToken{client}
}
relationship OneToOne{
ClientProfile{client} to AuthClient
}
This way you get the foreign key column named as client_id and the field named as client.
You can then define also which field of the related entity will be used for display in the generated UI.
There is more to learn about relationships in the doc: https://www.jhipster.tech/jdl/relationships

Sequelize: Defining Associations

Reading the documentation of Sequelize I'm in some level confused, what Sequelize will provide automatically for us and what we need to explicitly tell it.
I have two models: User and Post. As you have guessed a User can have multiple Posts and a Post belongs only to one User. Setting the respective relationships will look so:
Post.associate = (models) => {
Post.belongsTo(models.users, {
as:'user',
foreignKey: {
name: 'user_id',
allowNull: false
}
}
}
User.associate = (models) => {
User.hasMany(models.posts, {
as:'posts',
onDelete:'CASCADE',
onUpdate:'CASCADE'
}
}
My question is: should I specify the foreignKey one more time when declaring the hasMany association, or it is enough for Sequelize to have the foreignKey in one of the declared relationships between two models (in the example - belongsTo)?
From what I think happens:
Sequelize goes through all your association one by one
If you already provided a foreign key name then fine
Else it will guess/name the foreign key on its own
Like what it says about options.foreignKey in docs e.g. for belongsTo : https://sequelize.org/master/class/lib/model.js~Model.html#static-method-belongsTo (same description for hasOne, hasMany, belongsToMany )
options.foreignKey || string OR object || optional
The name of the foreign key attribute in the source table or an object representing the type definition for the foreign column (see Sequelize.define for syntax). When using an object, you can add a name property to set the name of the column. Defaults to the name of target + primary key of target
If sequelize is guessing your foreignKey names then you will face issues only if your foreignKey name is not matching (tableName + Id) OR (tableName + _ + id)
💡 Hence, better to give foreignKey names on your own to both sides of associations to never face any issues going further.

sequelize postgress bulk insert ignore if exist

I have following code
await tbl.bulkCreate(response.data, {
ignoreDuplicates: true
});
in response.data there is array of object.
What I expect it should check all the fields found duplicate do not insert,
What I am think it working like if Id exist ignore
I Think this ignoreDuplicates is not working due to id field which is always new for new record
Is there anyway I can say that check certain fields if that exist do not insert else insert
Thanks
Ignore duplicate values for primary keys? (not supported by MSSQL or Postgres < 9.5)
check your postgres version or you can use
{updateOnDuplicate : true}
try with composite key
queryInterface.addConstraint('Items', ['col1', 'col2'], {
type: 'unique',
name: 'custom_unique_constraint_name'
});

How to structure nested arrays with postgresql

I'm making a simple multiplayer game using postgres as a database (and node as the BE if that helps). I made the table users which contains all of the user accounts, and a table equipped, which contains all of the equipped items a user has. users has a one -> many relationship with equipped.
I'm running into the situation where I need the data from both tables structured like so:
[
{
user_id: 1,
user_data...
equipped: [
{ user_id: 1, item_data... },
...
],
},
{
user_id: 2,
user_data...
equipped: [
{ user_id: 2, item_data... },
...
],
},
]
Is there a way to get this data in a single query? Is it a good idea to get it in a single query?
EDIT: Here's my schemas
CREATE TABLE IF NOT EXISTS users (
user_id SERIAL PRIMARY KEY,
username VARCHAR(100) UNIQUE NOT NULL,
password VARCHAR(100) NOT NULL,
email VARCHAR(100) NOT NULL,
created_on TIMESTAMP NOT NULL DEFAULT NOW(),
last_login TIMESTAMP,
authenticated BOOLEAN NOT NULL DEFAULT FALSE,
reset_password_hash UUID
);
CREATE TABLE IF NOT EXISTS equipment (
equipment_id SERIAL PRIMARY KEY NOT NULL,
inventory_id INTEGER NOT NULL REFERENCES inventory (inventory_id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users (user_id) ON DELETE CASCADE,
slot equipment_slot NOT NULL,
created_on TIMESTAMP NOT NULL DEFAULT NOW(),
CONSTRAINT only_one_item_per_slot UNIQUE (user_id, slot)
);
Okay so what I was looking for was closer to postgresql json aggregate, but I didn't know what to look for.
Based on my very limited SQL experience, the "classic" way to handle this would just to do a simple JOIN query on the database like so:
SELECT users.username, equipment.slot, equipment.inventory_id
FROM users
LEFT JOIN equipment ON users.user_id = equipment.user_id;
This is nice and simple, but I would need to merge these tables in my server before sending them off.
Thankfully postgres lets you aggregate rows into a JSON array, which is exactly what I needed (thanks #j-spratt). My final* query looks like:
SELECT users.username,
json_agg(json_build_object('slot', equipment.slot, 'inventory_id', equipment.inventory_id))
FROM users
LEFT JOIN equipment ON users.user_id = equipment.user_id
GROUP BY users.username;
Which returns in exactly the format I was looking for.

proper way to reference documents with Mongoose

I see in all examples the suffix "_id" on a field referencing to another document.
Example:
record: {
_id : ObjectId("57f2fb5d1c6c3b0de45b170e",
artist_id: "prince" )
}
artist: {
_id: "prince"
}
Being that my artist mongo Schema has the "unique" attribute on the name field.
Is it Ok to things like below ?
record: {
_id : ObjectId("57f2fb5d1c6c3b0de45b170e",
artist: "prince" )
}
artist: {
_id : ObjectId(6eygdqzd5d1c6c3b0de45b1s0r",
name: "prince"
}
Or should you always reference directly the Id like in the first example?
if you visualize your problem in RDBMS world, there too to establish a foreign key constraint the field should be primary key in the referenced table and the same rule applies here.
now in your artist document though each document is going to contain a unique artist name but the name field itself is not key (primary key) but the ID is.
hence you have to establish the reference using the _id field.
what you can do is for ease if you want rather than relying on the mongodb generated ID field you can probably use name as the _id.

Resources