'Validation Error: Using global entity manager instance methods for context specific actions is disallowed

Using TypeORM and getting this error:


ValidationError: Using global EntityManager instance methods for context specific actions is disallowed.
If you need to work with the global instance's identity map, use `allowGlobalContext` configuration option or `fork()` instead

The code that it corresponds to is below:


import { MikroORM } from "@mikro-orm/core";
import { __prod__ } from "./constants";
import { Post } from "./entities/Post";
import mikroConfig from "./mikro-orm.config";

const main = async () => {
  const orm = await MikroORM.init(mikroConfig);
  const post = orm.em.create(Post, {
    title: "my first post",
  });
  await orm.em.persistAndFlush(post);
  await orm.em.nativeInsert(Post, { title: "my first post 2" });
};

main().catch((error) => {
  console.error(error);
});

I am unsure where I need to use the .fork() method



Solution 1:[1]

After doing some digging I found this solution:

  1. yarn install dotenv

  2. create a .env file in the root of the project

  3. In your .env file paste the following:

MIKRO_ORM_ALLOW_GLOBAL_CONTEXT = true

Problem solved!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dan JamesEngineer