Guide on setting up factories with pre-existing relationships in MIKRO-ORM

Hey there! I'm currently exploring how to set up a factory and establish relationships between models.

For instance, I have a UserFactory that corresponds to the User entity which is connected to the userType table. However, in the factory, I'm unable to access the EntityManager to locate any existing entries.

export class UserFactory extends Factory<User> {
  model = User
  definition(faker: Faker): Partial<User> {

    const user = {
      firstName: faker.name.firstName(),
      lastName: faker.name.lastName(),
      ...
      userType: // My challenge here is something like this:
                // EntityManager.findOne(UserType, {id: 1}}
                // But since EntityManager is private in Factory class, I'm stuck
    }

    return user
  }
}

I also attempted the following approach but encountered an error message: ValidationError: Value for User.type is required, 'undefined' found DatabaseSeeder

export class DatabaseSeeder extends Seeder {

  async run(em: EntityManager): Promise<void> {

    const users: User[] = new UserFactory(em).each(async user => {

      const userType : UserType| null = await em.findOne(UserType, 1)
      console.log(tenant)

      const userType = await em.findOne(UserType, 1)
      if (userType !== null) {
        user.type = userType
      } else {
        user.type = em.create(UserType, {
          type: 'test'
        })
      }

    }).make(10)

  }
}

What would be the correct way to resolve this issue? Your insights are greatly appreciated!

Answer №1

Utilize the shared seeder context outlined in the documentation:

export class AuthorSeeder extends Seeder {
  async run(em: EntityManager, context: Dictionary): Promise<void> {
    // store the entity in the context
    context.author = em.create(Author, {
      name: '...',
      email: '...',
    });
  }
}

export class BookSeeder extends Seeder {
  async run(em: EntityManager, context: Dictionary): Promise<void> {
    em.create(Book, {
      title: '...',
      author: context.author, // utilize the entity from context
    });
  }
}

The shared context can also be leveraged in the seeder factories. However, you have the flexibility to handle it yourself since both the seeder and factory are your implementations. Thus, you can pass any additional options as needed. You are the one initializing the factory, so there may not be a better way than incorporating it into your code.

I recommend avoiding excessive flush and findOne operations within your seeder. Strive for a single flush and rely on the shared context for entity retrieval instead.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting an environment map in Three.js can replace the original texture on a model

I'm having trouble setting an environment map to an OBJ model. It seems like the appearance has changed drastically! In its usual view, it looks like this: https://i.sstatic.net/4VcIG.png But when I set the environment map, it transforms into this: ht ...

Update the dropdown menu based on the revised time

I need to create a PHP site and JavaScript function that changes a dropdown menu based on specific time intervals, such as 7:00-8:00 (id530), 13:00-15:00 (id1330), or 20:00-03:00 (id2130). For example, if the time is 7:31, the dropdown menu should display/ ...

Pressing the enter key does not submit the Vue.js form

When attempting to submit the form by pressing "enter" on the keyboard, it only works when I click the "submit" button. I made sure to add @submit to the form event to ensure it triggers, but upon checking a log, I found that it only triggers when clicking ...

Converting a JSON format with JavaScript

As the data for a simple online store is extracted from a headless CMS, it is structured in the following format: [ { "id": 12312, "storeName": "Store1", "googleMapsUrl": "https://example1.com", "country": "Australia", ...

Display jpg images while authenticating using nextauth version 4.22.1

Hello everyone, I am currently working on displaying images with authentication using nextauth 4.22.1, as mentioned in the title. I have set up the new /app directory within the /src directory. While it occasionally works, most of the time it does not. H ...

How can we convert milliseconds to the corresponding date and time zone in Java?

1)I am trying to determine the user's timezone and current time using the following code snippets: Calendar currentdate1 = Calendar.getInstance(); TimeZone tz = Calendar.getInstance().getTimeZone(); System.out.println("time zone"+tz); System.out.pri ...

The JavaScript code functions perfectly when inputted directly into the Chrome Developer Console and executed, however, encounters an error when run from the index.html file using the src tag

I am starting from scratch with web development. On my page, there is an image carousel with two buttons for navigating between different images. When I use Brackets live preview to test my website, I encounter the following error message. Uncaught TypeErr ...

Do arrays permanently retain the strings stored within them?

As an 11-year-old who has been learning Javascript for the past month and a half, I am currently working on creating a login/register system. Right now, my focus is on the register part. I have a question: when adding a string/number/boolean to an array, d ...

What is the process for uploading files from NextJS directly from the browser to either Cloud Storage or an FTP server?

Is there a way to upload files from the browser using NextJS directly to Cloud Storage or an FTP server? I'm looking to upload files directly from the browser to a storage server. Do you think I can utilize node-ftp in the API routes of Nextjs, like ...

Re-enable the jQuery-ui sortable feature after it has been turned off

Here is a snippet of my jQuery code: var status = true; $('#edit').click(function () { if (status) { $('table tbody').sortable({ axis: 'y', update: function (event, ui) { va ...

Populate an ng-repeat table again while maintaining its original sorting order

Incorporating a table filled with data fetched from a webservice using the ng-repeat directive, I have enabled sorting functionality for all columns. Additionally, at regular intervals, the application polls the webservice to retrieve updated data. This o ...

Error message: Unable to locate Bootstrap call in standalone Angular project after executing 'ng add @angular/pwa' command

Having an issue while trying to integrate @angular/pwa, it keeps showing me an error saying "Bootstrap call not found". It's worth mentioning that I have removed app.module.ts and am using standalone components in various places without any module. Cu ...

Transforming numerical figures into written form within a specified range: A step-by-step guide

I have a unique custom range design that I have personally customized. Beneath each step of the range, there is a value displayed in a stylish green box. https://i.sstatic.net/vzeRK.png My query is regarding how I can replace the numeric values with tex ...

What is the method for including the `meta:redirect` or `<meta http-equiv="refresh" content="0; url=http://example.com" />` in the metadata object for Next.js version 13?

In order to redirect users from one of my pages, I previously utilized the redirect metatag. However, I am unable to locate similar options within the metadata API in Next.js 13 for the appRouter. ...

Link a list separated by commas to checkboxes in Angular 9

Within my reactive form, I am binding a checkbox list to an array using the following structure: {id:number, name:string}. TS ngOnInit(): void { this.initFCForm(); this.addCheckboxes(); } initFCForm(): void { this.fcForm = this.formBuilder.group({ fr ...

Response coming from an ajax call in the form of a JSON

With the JSON string provided below: {cols:[{"id":"t","label":"Title","type":"string"},{"id":"l","label":"Avg ","type":"string"},{"id":"lb","label":"High","type":"string"},{"id":"lo","label":"Low","type":"string"}],rows:[{"c":[{"v":"Change navigation"},{"v ...

Can TypeORM create an entity for a many-to-many relationship that functions like ActiveRecord's join table concept?

Consider a scenario where there is a Guardian entity connected to a Student entity. The goal is to establish their many-to-many relationship in TypeORM by introducing a new entity called StudentGuardianRelationship. This intermediary entity serves the purp ...

"Troubleshooting: Why is the JavaScript canvas.toDataURL method returning an

While I know this question has been asked multiple times before, I still haven't been able to find a solution. My goal is to take an image, rotate it, and place it in an HTML canvas. To achieve this, I am utilizing another canvas where I rotate the i ...

What is the best way to elegantly finish a live CSS animation when hovering?

Currently, I am working on a planet orbit code where I want to enhance the animation speed upon hover. The goal is for the animation to complete one final cycle at the new speed and then come to a stop. I have been successful in increasing the speed on hov ...

Easily transform checkboxes into images using jQuery with no need for external plugins

Is it possible to replace checkboxes with images without using jQuery plugins? I'm hoping to achieve this in just a few lines of code. Thank you. ...