1

Is their any possibility to use mongoDB ObjectID system with MySql and typeORM instead of using an incremental ID?

The goal would be to define my entity like this:

@Entity()
export class RolePermission implements IRolePermission {
    @ObjectIdColumn() id?: ObjectID;

    @Column()
    @IsNotEmpty()
    roleId: ObjectID;

    @Column()
    @IsNotEmpty()
    permissionId: ObjectID;
}

My entities could therefore have an ID without even being persisted. The ObjectId system would prevent collisions on the unique constraint I'd like to use for this column.

If a system like that can be implemented, is their any performance downside? I remember implementing such a system with PHP, and at the time, I had read this response that made me think that it was ok: Is there a REAL performance difference between INT and VARCHAR primary keys?

Hammerbot
  • 15,696
  • 9
  • 61
  • 103

1 Answers1

1

It's in fact really simple. You just need to use the ObjectID object from the mongodb package and declare your entities like you would do usually.

First, install mongodb dependencies:

yarn add mongodb
yarn add @types/mongodb

Then, declare your entity. Here an example with a working relationship between a user and an article:

user.entity.ts:

import { Entity, Column, ManyToOne, PrimaryColumn } from 'typeorm';
import { Article } from './article.entity';
import { ObjectID } from 'mongodb';

@Entity()
export class User {
    constructor() {
        this.id = (new ObjectID()).toString();
    }

    @PrimaryColumn()
    id: string;

    @Column({ length: 500 })
    username: string = null;

    @OneToMany(type => Article, article => article.user)
    articles: Article[];
}

article.entity.ts:

import { Entity, Column, ManyToOne, PrimaryColumn } from 'typeorm';
import { User } from './user.entity';
import { ObjectID } from 'mongodb';

@Entity()
export class Article {

    constructor() {
        this.id = (new ObjectID()).toString();
    }

    @PrimaryColumn()
    id: string;

    @Column({ length: 500 })
    title: string = null;

    @ManyToOne(type => User, user => user.articles, {nullable: true})
    user: User;
}

And use it as you would normally do:

const user = new User();
user.username = 'email@adress.com';

const article = new Article();
article.title = 'Mon titre';
article.user = user;

await this.userRepository.save(user);
await this.articleRepository.save(article);
Sylvain Attoumani
  • 1,213
  • 1
  • 15
  • 34