TypeORM - postgresSQL / saving data in the DB - postgresql

So, i'm new into this typeORM thing, and actually also new into postgresSQL DB, and there's something i couldn't undertand about typeORM and making relations between tables.
My Question: So, i have two entities, User and Post. When you create a post, we store the user ( creator of the post ) in the DB using #JoinColumn, and when i go to users table, i can see the name of that field (username), but, inside User entity, we have an array of Posts, but, that field doesn't appear in the postgres DB, so, when i create a relation, #ManyToOne and #OneToMany, what data stores in the DB and which don't ? Besides that, when i fetch stuff, i can fetch the array, but, does that array is store in the DB or what ? I'm kinda confused with this, so, now let me show you the code
User entity
import {
Entity as TOEntity,
Column,
Index,
BeforeInsert,
OneToMany
} from "typeorm";
import bcrypt from "bcrypt";
import { IsEmail, Length } from "class-validator";
import { Exclude } from "class-transformer";
import Entity from "./Entity";
import Post from "./Post";
#TOEntity("users")
export default class User extends Entity {
constructor(user: Partial<User>) {
super();
Object.assign(this, user);
}
#Index()
#IsEmail(undefined, { message: "Must be a valid email address" })
#Length(5, 255, { message: "Email is empty" })
#Column({ unique: true })
email: string;
#Index()
#Length(3, 200, { message: "Must be at leat 3 characters long" })
#Column({ unique: true })
username: string;
#Exclude()
#Length(6, 200, { message: "Must be at leat 3 characters long" })
#Column()
password: string;
#OneToMany(() => Post, post => post.user)
posts: Post[];
#BeforeInsert()
async hashedPassword() {
this.password = await bcrypt.hash(this.password, 6);
}
}
Post entity
import {
Entity as TOEntity,
Column,
Index,
BeforeInsert,
ManyToOne,
JoinColumn,
OneToMany
} from "typeorm";
import Entity from "./Entity";
import User from "./User";
import { makeid, slugify } from "../util/helpers";
import Sub from "./Sub";
import Comment from "./Comment";
#TOEntity("posts")
export default class Post extends Entity {
constructor(post: Partial<Post>) {
super();
Object.assign(this, post);
}
#Index()
#Column()
identifier: string; // 7 Character Id
#Column()
title: string;
#Index()
#Column()
slug: string;
#Column({ nullable: true, type: "text" })
body: string;
#Column()
subName: string;
#ManyToOne(() => User, user => user.posts)
#JoinColumn({ name: "username", referencedColumnName: "username" })
user: User;
#ManyToOne(() => Sub, sub => sub.posts)
#JoinColumn({ name: "subName", referencedColumnName: "name" })
sub: Sub;
#OneToMany(() => Comment, comment => comment.post)
comments: Comment[];
#BeforeInsert()
makeIdAndSlug() {
this.identifier = makeid(7);
this.slug = slugify(this.title);
}
}
How the User entity looks as a table in the DB
So, as you can see, there's no field with name posts ( which is weird, because as i already said, if i can fetch that, where is that data if i can't see it in the DB )
Now, let me show you Post entity
What i want to understand: So, we have the relationship between tables, know, i tried to search stuff in order to understand that, but i couldn't find anything, so, if you can help me with this mess, i would really aprecciate that, so, thanks for your time !

Let's take this section and try to understand piece by piece:
#ManyToOne(() => User, user => user.posts)
#JoinColumn({ name: "username", referencedColumnName: "username" })
user: User;
1. #ManyToOne(() => User, user => user.posts):
#ManyToOne: This annotation tells typeORM that Post entity is going to have a many to one relationship. From the postgres DB point of view, this means that posts table is going to have a new column (foreign key) which points to a record in some other table.
() => User: This is called definition of the target relationship. This helps typeORM to understand that the target of the relationship is User entity. For postgres DB, this means the foreign key in posts table is going to reference a row in users database
user => user.posts: This is called the inverse relationship. This tells typeORM that the related property for the relationship in User entity is posts. From the postgres DB point of view, this has no meaning. As long as it has the foreign key reference, it can keep the relationship between the two tables.
2. #JoinColumn({ name: "username", referencedColumnName: "username" }):
#JoinColumn: In this scenario, this annotation helps typeORM to understand the name of the foreign key column in posts table and the name of the referenced column in users table
name: "username": This is the name of the column in posts table which is going to uniquely identify a record in users table
referencedColumnName: "username": This is the name of the column in users table which is going to be referenced by the foreign key username in posts table.
inside User entity, we have an array of Posts, but, that field doesn't appear in the postgres DB
The array of Posts is there for the typeORM to return you an array of linked posts. It is not needed by postgres DB to contain the relationship.
when i create a relation, #ManyToOne and #OneToMany, what data stores in the DB and which don't
Whatever property you decorated using #Column will be there in the table as it is. And for the relationships, only the foreign key will be saved. As an example, when you save a Post entity, it will save only the relevant columns in that entity + username foreign key.
when i fetch stuff, i can fetch the array, but, does that array is store in the DB or what ?
When you query User entity, typeorm uses the annotations to join users table with posts table and return you the posts with the user you searched. But in database, it saves users and posts data in their respective tables and uses username foreign key to keep the relationship between them.
I hope this helps you to understand what happens. Cheers 🍻 !!!

Related

Get related data from another typeorm table (Adminjs integration)?

Is it possible in TypeORM, PostgreSQL, AdminJs with One to Many table relationships to immediately receive data from the associated table, and not a link to this data, as in my example.
#Entity()
export class User extends BaseEntity {
#PrimaryGeneratedColumn()
id: number;
#Column({ unique: true })
userColum: string;
#OneToMany(() => Car, (car) => car.car)
cars: Car[];
}
Car:----------------------------
#Entity()
export class Car extends BaseEntity {
#PrimaryGeneratedColumn()
id: number;
#ManyToOne(() => User, (user: User) => user.userColum, { eager: true })
car: Car;
#Column()
name: string;
}
ТI get a link here:
#ManyToOne(() => User, (user: User) => user.userColum, { eager: true })
But I would like to pull up the data itself. This seems to require an additional request.
Or will you have to somehow custom make the request yourself?
If yes, how can this be done?
Next I use AdminJS to display data and act on tables
I'm using AdminJS for the front-end (This requirement is not made by me.
Therefore, I do not have routes, this is done by AdminJS under the hood.
I did not find any mention of my situation in the AdminJS documentation.
At the moment it turns out that instead of the desired data is the value from the userColum column, when I display the Cars table in a column called CarId, I get a reference to userColum. The link is displayed as an index of the Users table - 1, 2, 3 and is clickable.
Here, instead of displaying 1, 2, 3, I want to see the text value “userColum 1”, “userColum 2”, “userColum 3”, which are in the Users column userColum.
Accordingly, when I click on the link, I get the necessary data of the userColum column. And I want the data to be immediately displayed inside the Cars table.
If we remove { eager: true }
Then in the database in the Cars table in the CarId column there will be id from the Users table, but nothing is displayed on the front-end AdminJs.
I believe you have a mistake in your Car entity (and a possible bad practice in User entity)
the mistake - it should be
#ManyToOne(() => User, (user: User) => user.cars, { eager: true })
user: User; // not car: Car;
and bad naming
#OneToMany(() => Car, (car) => car.user) // not car.car
cars: Car[];
Also, it would be helpful to know how you are querying this data. According to the docs
you must specify the relation in FindOptions
Like so:
const userRepository = dataSource.getRepository(User)
const users = await userRepository.find({
relations: {
cars: true,
},
})

How can I query/update only Junction table in nestjs using TypeOrm?

I have two tables with #ManyToMany relation between them:
#Entity()
export class Category {
#PrimaryGeneratedColumn()
id: number;
#ManyToMany(() => Question, question => question.categories)
questions: Question[];
}
#Entity()
export class Question {
#PrimaryGeneratedColumn()
id: number;
#ManyToMany(() => Category, category => category.questions)
#JoinTable({
name: "question_categories",
joinColumn: {
name: "question",
referencedColumnName: "id"
},
inverseJoinColumn: {
name: "category",
referencedColumnName: "id"
})
categories: Category[];
}
As we know we should have 3 tables for such relation and one them would be junction table question_categories. So my question is - can I somehow query that junction table to update? Or how and what should I do to be able to update junction table rows?
Here is what I did. I added a separate entity for question_categories and set #ManyToOne relation to the tables, also did the opposite in the main tables - categories and questions. But when I did that I'm getting error when trying to create new relation.

How to disable automatic downcasing in NestJS' typeORM query to my postgres DB?

I am using TypeORM to create and manage my DataBase using TypeORM Entities.
I have a very peculiar relation as such
#Entity()
export class User extends BaseEntity {
#PrimaryGeneratedColumn()
id: number;
#Column()
login: string;
#Column()
nickname: string;
#Column()
wins: number;
#Column()
looses: number;
#Column()
current_status: string;
#ManyToMany(() => User)
#JoinTable()
friends: User[];
#ManyToMany(() => MatchHistory)
#JoinTable()
match_histories: MatchHistory[];
}
Where User has a ManyToMany relationship with itself. Because of this, typical tools do not work correctly (I haven't found a way to access a User's friends with TypeORM's tools).
So I am doing a good old SQL request as such:
const res = await this.manager.query("SELECT * FROM user WHERE user.id IN (SELECT F.userId_2 AS Friends FROM user_friends_user F WHERE F.userId_1=?);", [user.id]);
This can be translated as "get all the users who's ID is in the friend list of user user.
The problem is that I have noticed that all my requests seem to be downcased. When doing this I face the column f.userid_2 does not exist.
I do not know if it is TypeORM or Postgres which downcases my requests, all I want is it to stop doing so. Thank you very much !
This is something Postgres does by default. If you need to use uppercase values, you need to pass a string literal to Postgres. In your case, that would look like
const res = await this.manager.query(
'SELECT * FROM user WHERE user.id IN (SELECT "F"."userId_2" AS "Friends" FROM user_friends_user "F" WHERE "F"."userId_1"=?);',
[user.id]
);

TypeOrm Many to Many of the same entity

I'm trying to figure out how to create a User Entity with a relation on the friends column that contains other User entities. Joined through a join table of userId pairs.
This sort of works:
#Entity('user')
export class User {
#PrimaryGeneratedColumn('uuid')
id: string;
#ManyToMany(
() => User,
(user) => user.friends
)
#JoinTable()
friends: User[];
}
It does create a relation and I can populate the join table with ids and retrieve the data but it seems to be only one way.
Here is the join table:
userId_1 | userId_2
------------+------------
What I mean by one way is that it the linkage appears to be from userId_1 -> userId_2 and not both ways.
Is there any way to improve on this? I'd like to be able to get the relation from either side based on the one row entry
You need to add the other side of the relation. I'm using "followers" instead of "friends" since that reflects clearly the direction each relation has.
This way you can do something like user.followers and user.following
#ManyToMany(() => User, (user) => user.following)
#JoinTable()
followers: User[];
#ManyToMany(() => User, (user) => user.followers)
following: User[];

Populate a query in Mongoose with Schema First approach and NestJS

First off I want to say this question is similar to this one which references this one. I have the exact same question as the second link except a notable difference. I'm trying to extend a class generated by NestJS which defines a property.
I'm using NestJs with the Schema first approach found here. I'm also generating a classes file based on my GraphQL Schema.
Here is the Schema:
type Location {
name: String!
owner: User!
}
Which generates the class:
export class Location {
name: string;
owner: User;
}
Now, I want to extend this class so I don't have to repeat the data (there are a lot more fields not shown). I also I want to add fields that live on a document but are not in the schema (_id in this example). Here is my LocationDocument and my schema.
export interface LocationDocument extends Location, Document {
_id: Types.ObjectId
}
export const LocationSchema: Schema = new Schema(
{
name: {
type: String,
required: true,
},
owner: {
type: Types.ObjectId,
ref: 'User',
}
);
Now here is my issue. The generated Location class from the GraphQL schema defines the owner property as a User type. But in reality it's a just a mongodb id until it is populated by Mongoose. So it could be a Types.ObjectId or a User on a UserDocument. So I attempted to define it as:
export interface LocationDocument extends Location, Document {
_id: Types.ObjectId
owner: User | Types.ObjectId;
}
But this throws an error in the compiler that LocationDocument incorrectly extends Location. This makes sense. Is there any way to extend the User Class but say that owner property can be a User Type (once populated by Mongoose) or a mongo object ID (as is stored in the database).
I decided that having a property that can be both types, while easy with Mongoose and JS, isn't the typed way. In my schema I have an owner which is a User type. In my database and the document which extends it, I have an OwnerId. So to people accessing the API, they don't care about the ownerId for the relationship. But in my resolver, I use the Id. One is a Mongo ID type, the other is a User type.