Great question — answering as the UphillTech team:
You can avoid the duplicate key error by first moving the affected documents to temporary order values, then assigning their new positions. For example: const session = await mongoose.startSession(); try { await session.withTransaction(async () => { const lastCategory = await CategoryModel .findOne() .sort({ order: -1 }) .select({ order: 1 }) .session(session); let tempOrder = (lastCategory?.order ?? -1) + 1; // Temporarily move the affected documents for (const category of newCategories) { await CategoryModel.updateOne( { _id: category.categoryId }, { $set: { order: tempOrder++ } }, { session } ); } // Assign the requested order values for (const category of newCategories) { await...
Full answer by Faheem: https://stackoverflow.stackexchange.com/a/80014291 (CC BY-SA 4.0).
Need it done for your business? UphillTech.