in mikroorm when I try to insert record it do update statement

103 Views Asked by At

I am try to use mikroorm with nest js

import { Migrator } from '@mikro-orm/migrations';
import { defineConfig } from '@mikro-orm/postgresql';
import { TsMorphMetadataProvider } from '@mikro-orm/reflection';
import 'dotenv/config';

export default defineConfig({
  clientUrl: process.env.DATABASE_URL,
  entities: ['./dist/**/*.entity.js'],
  entitiesTs: ['./src/**/*.entity.ts'],
  debug: true,
  metadataProvider: TsMorphMetadataProvider,
  extensions: [Migrator],
  migrations: {
    path: './dist/migrations',
    pathTs: './src/migrations',
    disableForeignKeys: false,
    snapshot: false,
  },
});

I have article entity

import { BeforeCreate, Entity, ManyToOne, Property, t, EventArgs, PrimaryKey } from '@mikro-orm/core';
import { BaseEntity } from '../../../abstract/base.entity';
import { User } from '../../user/entities/user.entity';
import { convertToSlug } from './../../../utilities/create-slug';

@Entity()
export class Article {
  @PrimaryKey()
  id!: number;

  @Property()
  createdAt = new Date();

  @Property({ onUpdate: () => new Date() })
  updatedAt = new Date();

  @Property({ unique: true })
  slug!: string;

  // @Property()
  @Property({ index: true })
  title!: string;

  @Property({ length: 1000 })
  description!: string;

  @Property({ type: t.text, lazy: true })
  text!: string;

  // @ManyToOne({ nullable: true })
  //   @ManyToOne(() => User)
  //   @ManyToOne('User')
  // @ManyToOne({ entity: () => User, nullable: true, inversedBy: 'articles' })
  // author?: User;

  @BeforeCreate()
  createSlug() {
    this.slug = convertToSlug(this.title);
  }

  createDescription(args: EventArgs<Article>) {
    const description = args.changeSet.payload.description;
    if (!description) this.description = this.text.slice(0, 999) + '...';
  }
}

when I try to create articles with the following code

import { Injectable, NotFoundException } from '@nestjs/common';
import { CreateArticleDto } from './dto/create-article.dto';
import { UpdateArticleDto } from './dto/update-article.dto';
import { Article } from './entities/article.entity';
import { InjectRepository } from '@mikro-orm/nestjs';
import { EntityManager, EntityRepository, wrap } from '@mikro-orm/postgresql';
import { User } from '../user/entities/user.entity';

@Injectable()
export class ArticleService {
  constructor(
    @InjectRepository(Article) private readonly repo: EntityRepository<Article>,
    private readonly em: EntityManager,
  ) {}

  // async create(createArticleDto: CreateArticleDto) {
  //   const _em = this.em.fork();
  //   console.log(' ~ ArticleService ~ create ~ createArticleDto:', _em._id);
  //   const { authorId, ...payload } = createArticleDto;
  //   const article = _em.create(Article, payload);
  //   // const article = new Article();
  //   // wrap(article).assign(payload);

  //   // if (authorId) {
  //   // // work only one time, fail in second time
  //   //   const userRef = _em.getReference(User, authorId);
  //   //   console.log(' ~ ArticleService ~ create ~ userRef:', userRef);
  //   //   article.author = userRef;
  //   // }

  //   if (authorId) {
  //     // work only one time, fail in second time
  //     const user = await _em.findOne(User, { id: authorId });
  //     article.author = user;
  //   }

  //   await _em.persistAndFlush(article);
  //   console.log(' ~ ArticleService ~ create ~ article:', article);
  //   return article;
  // }

  async create(createArticleDto: CreateArticleDto) {
    const _em = this.em.fork();
    console.log(' ~ ArticleService ~ create ~ createArticleDto:', _em._id);
    let article: Article;

    await _em.transactional(async (em) => {
      const { authorId, ...payload } = createArticleDto;
      article = em.create(Article, payload);
      if (authorId) {
        // work only one time, fail in second time
        const userRef = em.getReference(User, authorId);
        console.log(' ~ ArticleService ~ create ~ userRef:', userRef);
        // article.author = userRef;
      }

      await em.persistAndFlush(article);
    });
    // const article = new Article();
    // wrap(article).assign(payload);

    // if (authorId) {
    // // work only one time, fail in second time
    //   const userRef = _em.getReference(User, authorId);
    //   console.log(' ~ ArticleService ~ create ~ userRef:', userRef);
    //   article.author = userRef;
    // }

    // if (authorId) {
    //   // work only one time, fail in second time
    //   const user = await _em.findOne(User, { id: authorId });
    //   article.author = user;
    // }

    // await _em.persistAndFlush(article);
    console.log(' ~ ArticleService ~ create ~ article:', article);
    return article;
  }
}

It work normally for one or twice then it try to create more articles it do update statement instead of insert !! why this happen and how to solve it ?

I try to create article with different ways, also try to disable relation to investigate the problem

0

There are 0 best solutions below