node.jstypescriptgraphqlmikro-orm

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


Using MikroORM 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

  • I faced a similar issue today when I upgraded the mikrorm setup from v4 to v5. After doing some RnD, I found the following changes helped me solve the mentioned error.

    1. In the config object which is passed to the MikroORM.init call, pass the following property

    allowGlobalContext: true

    1. Don't directly use em to create database entry. Instead use the following code
    const post = orm.em.fork({}).create(Post, {
        title: "my first post",
      });
    

    The above changes should help you fix the error.

    I am also very new to MikroORM. so, I am not sure why this error appears. But my uneducated guess is, they are restricting access to any changes to the global EntityManager em instance.