0

I'm using migrate-mongo and get the following error when trying to run some migrations.

~$ npx migrate-mongo up
ERROR: Could not migrate up 20221201223533-add-indexes.js: Cannot create new
  indexes on existing collection xxx.xxx in a multi-document transaction.
  MongoServerError: Cannot create new indexes on existing collection xxx.xxx in
  a multi-document transaction.

Googling the error comes up with zero results. Similar questions about "Cannot do xyz in a multi-document transaction" seem to suggest the collections need to exist before running the transaction. I've checked and double checked to make sure the collections exist, but still get the above error.

My code looks something like this:

exports.up = async (db, client) => {
  const fooCollection = db.collection('foo')
  const barCollection = db.collection('bar')

  const session = client.startSession();
  try {
    await session.withTransaction(async () => {
      await fooCollection.createIndex({ foo: 1 }, { session });
      await barCollection.createIndex({ bar: 1 }, { session });
    });
  } finally {
    await session.endSession();
  }
}

exports.down = async (db, client) => { ... }

How can I create a new index within a transaction?

darksinge
  • 1,828
  • 1
  • 21
  • 32
  • 1
    The error message and [documentation on the topic](https://www.mongodb.com/docs/manual/core/transactions/#create-collections-and-indexes-in-a-transaction) seems pretty straightforward. Either use database version `4.4` or create the indexes outside of a transaction? – user20042973 Dec 02 '22 at 01:31
  • Thank you for pointing out the documentation. I'm using version `5.0.14` so that's not the issue. The doc link you provided says you cannot create an index on an existing non-empty collection within a transaction, so that seems to be the issue. – darksinge Dec 02 '22 at 16:38

1 Answers1

0

Thanks @user20042973 for pointing out the docs that explain the issue.

When creating an index inside a transaction [1], the index to create must be on either:

  1. a non-existing collection. The collection is created as part of the operation.

  2. a new empty collection created earlier in the same transaction.

Although this is disappointing, apparently it is not possible to create an index within a transaction on an existing, non-empty collection.

darksinge
  • 1,828
  • 1
  • 21
  • 32