upsert Method - Data Model Repository Reference

The upsert method of a data model repository creates or updates one or more records of the data model.

Note: This reference assumes you've already resolved the data model repository, as explained in the Data Model Repository Reference documentation.

upsert Parameters#

Loading...

Upsert Records#

Note: As of Medusa v2.11.0, MikroORM dependencies are included in the @medusajs/framework package. If you're using an older version of Medusa, change the import statement to @mikro-orm/knex.
Code
1import { 2  InjectTransactionManager,3  MedusaContext,4  MedusaService,5  InjectManager,6} from "@medusajs/framework/utils"7import { Context, InferTypeOf, DAL } from "@medusajs/framework/types"8import { EntityManager } from "@medusajs/framework/mikro-orm/knex"9import Post from "./models/post"10
11class BlogModuleService extends MedusaService({12  Post,13}){14  // ...15  @InjectTransactionManager()16  protected async doSomething_(17    id: string,18    @MedusaContext() sharedContext?: Context<EntityManager>19  ): Promise<any> {20    const posts = await this.postRepository_.upsert([21      {22        id: "01JSHAW6Z7KW4X6E8MFPGNEKHC",23        title: "My Old Post",24      },25      {26        title: "My New Post",27      },28    ])29
30    return posts31  }32
33  @InjectManager()34  async doSomething(35    id: string,36    @MedusaContext() sharedContext?: Context<EntityManager>37  ): Promise<any> {38    return await this.doSomething_(id, sharedContext)39  }40}

Parameters#

The upsert method accepts an array of objects, each representing a record to create or update.

If a record object has an id property, the method will try to update a record with that id. Otherwise, the method will create a new record.

If the id property is specified but no record with that id exists, the created record will have the specified id.

Each object has the same shape as the data model.

Returns#

The method returns an array of the created or updated records.

Was this page helpful?
Ask Bloom
For assistance in your development, use Claude Code Plugins or Docs MCP server in Cursor, VSCode, etc...FAQ
What is Medusa?
How can I create a module?
How can I create a data model?
How do I create a workflow?
How can I extend a data model in the Product Module?
Recipes
How do I build a marketplace with Medusa?
How do I build digital products with Medusa?
How do I build subscription-based purchases with Medusa?
What other recipes are available in the Medusa documentation?
Chat is cleared on refresh
Line break
⇧↵