When attempting to seed, the system could not locate any metadata for the specified "entity"

While working on a seeding system using Faker with TypeORM, I encountered an error during seeding:

🌱  TypeORM Seeding v1.6.1
✔ ORM Config loaded
✔ Factories are imported
✔ Seeders are imported
✔ Database connected
⠹ Executing CreateUsers Seeder
❌  Could not save entity
EntityMetadataNotFound: No metadata for "UsersEntity" was found.

✖ Could not run the seed CreateUsers!
Error: Could not save entity

error Command failed with exit code 1.

The seeding process is being done through the CLI of the typeorm-seeding npm package specified in my package.json

"seed": "yarn migration:up && cross-env CLI=true ts-node -r tsconfig-paths/register ./node_modules/typeorm-seeding/dist/cli.js ---root src/core/config -n database-configuration.ts seed",

I have a user.factory.ts file linked with the users.entity.ts file

define(UsersEntity, async (faker: typeof Faker) => {
  const user = new UsersEntity();
  user.firstName = faker.name.firstName();
  user.lastName = faker.name.lastName();
  user.email = faker.internet.email().toLowerCase();
  user.phone = faker.phone.phoneNumber();
  user.imageUrl = faker.image.people();
  user.password = await CryptoUtils.getHash('password');
  user.role = Role.User;
  return user;
});

Additionally, the user.seeder.ts file is responsible for handling the seeding process

export class CreateUsers implements Seeder {
  public async run(factory: Factory): Promise<any> {
    await factory(UsersEntity)().createMany(10);
  }
}

Lastly, here is the database configuration used for executing the seeding process via the CLI

return {
    type: 'postgres',
    host: process.env.POSTGRES_HOST,
    port: +process.env.POSTGRES_PORT,
    username: process.env.POSTGRES_USER,
    password: process.env.POSTGRES_PASSWORD,
    database: process.env.POSTGRES_DB,
    entities:
      process.env.NODE_ENV === 'test'
        ? ['src/**/*.entity.ts']
        : ['dist/**/*.entity{.ts,.js}'],
    synchronize: false,
    keepConnectionAlive: true,
    migrationsRun: true,
    logging: process.env.DATABASE_SHOW_SQL === 'true' || false,
    migrations:
      process.env.NODE_ENV === 'test'
        ? ['src/core/database/migrations/**/*.ts']
        : ['dist/core/database/migrations/**/*.js'],
    seeds: ['src/core/database/seed/seeder/**/*{.ts,.js}'],
    factories: ['src/core/database/seed/factory/**/*{.ts,.js}'],
    cli: {
      migrationsDir: 'src/core/database/migrations',
    },
};

Answer №1

To address this issue, I implemented a conditional check for NODE_ENV in both my factories and seeds files. This adjustment prevented the files from being retrieved from both the dist and src directories.

The root cause of the problem stemmed from operating in a development environment. Instead of locating the entities as expected in the factories and seeds directories within src, they were mistakenly found in the dist folder.

To remedy this situation, I updated the process.env.NODE_ENV check within the factories and seeds:

seeds:
    process.env.NODE_ENV === 'test'
        ? ['src/core/database/seed/seeder/**/*.ts']
        : ['dist/core/database/seed/seeder/**/*.js'],
factories:
    process.env.NODE_ENV === 'test'
        ? ['src/core/database/seed/factory/**/*.ts']
        : ['dist/core/database/seed/factory/**/*.js'],

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

Developing an Easy-to-Use PDF Popup Interface

I need a simple PDF modal where I can input the text: 'The sky is blue' and have it link to a PDF that opens up when clicked. I found a similar sample online, but it includes an image plus an image modal that pops up. I want to replace the imag ...

Several DIV elements lined up side by side

I've been working on a program that retrieves data from a database, lists some of the data when a button is clicked within the same div, and then creates new divs with buttons that have onclick events until it reaches a certain maximum value. To keep ...

Can you explain the purpose of App.hiddenDivs in jQuery code snippet provided?

Exploring various JQuery performance tips on this insightful website Do you happen to know the significance of App.hiddenDivs ? ...

Managing the synchronization of a time-consuming method in Angular using TypeScript

We are currently utilizing TypeScript and Angular 6 in our development project and have a service class that is injectable: @Injectable() export class ProductService { getAllProducts(): Observable<Product[]> { return this.http.get(' ...

What is the proper way to bring in Typescript types from the ebay-api third-party library?

My TypeScript code looks like this: import type { CoreItem } from 'ebay-api'; declare interface Props { item: CoreItem; } export default function Item({ item }: Props) { // <snip> } However, I encounter an issue when trying to build ...

Avoid the scenario in which JQuery .HTML replaces the existing .HTML content before it is shown

In my current implementation, I am using a multidimensional array to store values and loop through it based on specific criteria. This process involves determining if a number matches and if it has a set status, such as "487 Online." The data in the array ...

The functionality of .bind() is malfunctioning on both Microsoft Edge and Google Chrome browsers

Everything seems to be running smoothly on Mozilla (version 103.0), but unfortunately, it's not performing as expected on Chrome or Microsoft Edge. $('#loading').bind('ajaxStart', function () { $(this).show(); }).bind('ajaxS ...

Having difficulties including the Stack Overflow website within an iframe

I've been attempting to embed the Stack OverFlow website into an HTML page using an iFrame, but I'm running into some issues. Oddly, when I tried embedding my other two websites, they displayed correctly, but Stack OverFlow is not showing up on m ...

positioning newly generated dropped elements within the DOM structure dynamically

Hello everyone, I have a query related to drag and drop functionality. I am currently working on an application that allows users to create websites using only drag and drop features. I am facing a challenge in implementing a feature where users can drop e ...

Tips for handling an empty jQuery selection

Below is the code snippet: PHP CODE: if($data2_array[7]['status'] == "OK"){ $degtorad = 0.01745329; $radtodeg = 57.29577951; $dlong = ($lng - $supermercado_lng); $dvalue = (sin($lat * $degtorad) * sin($superm ...

Generate fresh JavaScript objects with customized properties

My goal is to use Javascript and JQuery to automatically create a new object with properties provided by the user when they fill out an HTML form. I have a constructor named "object" for this purpose. function object (prop1, prop2, prop3) { this.p ...

Sweetalert seems to have hit a roadblock and is not functioning properly. An error has been detected in its TS file

Currently, I am responsible for maintaining an application that utilizes Angular 7.0.7 and Node 10.20.1. Everything was running smoothly until yesterday when my PC unexpectedly restarted. Upon trying to run ng serve, I encountered the following error: E ...

Having issues with retrieving latitude and longitude data from the Geocoding API in Node.js when using the OpenWeather API

I attempted to create a program in node.js that utilizes the openweather API. The idea was for the user to input a city name, then use the Geocoding API to extract the latitude and longitude coordinates, and finally retrieve weather data from the current w ...

Ways to adjust the positioning of an image

Seeking assistance, I am currently working on building a portfolio using HTML while following a tutorial. I utilized undraw to insert an image but unfortunately, the image is fixed to the right-hand side: I would like to position the image below my icons, ...

Why is it that injecting javascript within innerHTML seems to work in this case?

According to the discussion on this thread, it is generally believed that injecting javascript in innerHTML is not supposed to function as expected. However, there are instances where this unconventional method seems to work: <BR> Below is an examp ...

Closing a Javascript-created popup using server-side code

I'm encountering an issue with closing a modal that I've created in JavaScript. The goal is to display a loading spinner while data is being fetched, and then hide it once the background process is complete. Everything functions correctly until t ...

Discovering and editing a specific line in Sheets: An in-depth look at the Message Counter

Currently, the bot checks if your ID already exists in the sheet list and adds you if it doesn't when someone writes a message in the chat. Now, I want the bot to implement a message counter in the sheet list. What would be the most effective way to ...

Class property in Typescript is initialized in the constructor, but is undefined in a member function

I'm encountering a recurring problem while developing an Electron application using Typescript. The backend has a set of controllers, with the AppController managing file system interactions and WindowController handling basic window functions. Here&a ...

Ways to modify the final sum exclusively for a single table

I am currently struggling to figure out how to calculate only the grand total of the first table using just one jQuery/JavaScript script. The code I am referencing is from: Below is the code snippet: <!DOCTYPE html> <html xmlns="http://www.w3 ...

Tips for initiating a function at a designated scroll point on a webpage

Currently, I am testing out a code snippet that allows images to flip through in a canvas element. I'm curious if it's possible to delay the image flipping effect until the viewer scrolls down to a specific section of the page where the canvas i ...