Mongodb Transactions - Unable to read from a snapshot

Viewed 1728

I am trying MongoDB transactions with mongoose but on every request to create a database and insert a user and a company, I am getting the following error

"Unable to read from a snapshot due to pending collection catalog changes; please retry the operation. Snapshot timestamp is Timestamp(1584451745, 1). Collection minimum is Timestamp(1584451753, 1)"

On retrying the request it works. But When I send a new request to create a new database and insert a user and a company, I get the same error. I always need to retry the request to successfully insert the data.

const session = await mongoose.startSession();
session.startTransaction();

try {
  await db.createCollection("users");
  await db.createCollection("companies");

  const savedUser = await UserModel({
    ...userDetails,
  }).save({ session });


  const company = await new CompanyModel({
    ...companyDetails
  }).save({ session });


  await session.commitTransaction();

  return { message: "User Added Successfully" };

} catch (err) {
  error("Transaction Error", err);
  await session.abortTransaction();
  throw err;
} finally {
  session.endSession();
}

Any idea what I am missing here?

1 Answers

Ok, I figured this out. As per mongoose documentation, you need to have collections created before using transactions:

Model.createCollection()
Parameters
[options] «Object» see MongoDB driver docs
[callback] «Function»
Create the collection for this model. By default, if no indexes are specified, mongoose will not create the collection for the model until any documents are created. Use this method to create the collection explicitly.

Note 1: You may need to call this before starting a transaction See https://docs.mongodb.com/manual/core/transactions/#transactions-and-operations

source: https://mongoosejs.com/docs/api.html#model_Model.createCollection

Related