Skip to content
Latchkey

MongoDB "Transaction numbers are only allowed on a replica set member" in CI

Multi-document transactions and retryable writes require a replica set (or a sharded cluster). A default standalone mongod in CI rejects them with "Transaction numbers are only allowed on a replica set member or mongos".

What this error means

A test that starts a session/transaction fails with "MongoServerError: Transaction numbers are only allowed on a replica set member or mongos" against a single-node CI mongod.

node
MongoServerError: Transaction numbers are only allowed on a replica set member or mongos
  code: 20, codeName: 'IllegalOperation'

Common causes

The CI mongod is a standalone, not a replica set

The service container runs a plain mongod with no --replSet, so it has no oplog and cannot support transactions.

rs.initiate() was never run

Even with --replSet, the set must be initiated once before it becomes primary and accepts transactions.

How to fix it

Run mongod as a single-node replica set

  1. Start mongod with --replSet rs0.
  2. Initiate the set once with rs.initiate().
  3. Point the URI at the set and enable transactions.
Terminal
mongod --replSet rs0 --dbpath /tmp/mongo-data --fork --logpath /tmp/mongod.log
mongosh --eval 'rs.initiate({_id:"rs0",members:[{_id:0,host:"localhost:27017"}]})'

Use mongodb-memory-server with a replSet

For Node tests, an in-memory replica set gives transactions without managing mongod.

test-setup.js
import { MongoMemoryReplSet } from 'mongodb-memory-server';
const replSet = await MongoMemoryReplSet.create({ replSet: { count: 1 } });
const uri = replSet.getUri();

How to prevent it

  • Run a single-node replica set in CI when tests use transactions.
  • Initiate the set once during startup, then wait for a primary.
  • Prefer mongodb-memory-server replSet mode for isolated Node tests.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →