# Fixing MongoDB Transaction Error in Node.js (Windows)

When working with Mongoose transactions in a Node.js project, you might encounter this error:

```plaintext
Transaction numbers are only allowed on a replica set member or mongos
```

This happens because **MongoDB transactions require a replica set**, even for local development. A fresh MongoDB installation on Windows runs as a standalone server that doesn't support transactions. Here's how to fix it.

* * *

## Why This Happens

MongoDB transactions depend on replication infrastructure for:

*   **Write durability**
    
*   **Rollback capability**
    
*   **Consistent snapshots**
    

Even with a single MongoDB instance, you need to configure it as a **single-node replica set**.

* * *

## The Solution: Enable Replica Set on Windows

### Step 1: Edit MongoDB Configuration

Open the MongoDB config file (usually at `C:\Program Files\MongoDB\Server\7.0\bin\mongod.cfg`) and add the replication settings:

```yaml
systemLog:
  destination: file
  path: C:\Program Files\MongoDB\Server\7.0\log\mongod.log
  logAppend: true

storage:
  dbPath: C:\Program Files\MongoDB\Server\7.0\data

net:
  bindIp: 127.0.0.1
  port: 27017

replication:
  replSetName: rs0
```

⚠️ **Important**: YAML is space-sensitive. Use spaces, not tabs.

### Step 2: Restart MongoDB Service

Open **Command Prompt as Administrator** and run:

```bash
net stop MongoDB
net start MongoDB
```

### Step 3: Initialize the Replica Set

Open a new Command Prompt and run:

```bash
mongosh
```

Once connected, initialize the replica set:

```javascript
rs.initiate();
```

You should see `{ ok: 1 }`.

Verify the status:

```javascript
rs.status();
```

Look for `"stateStr": "PRIMARY"` in the output.

### Step 4: Update Your Connection String

Update your Mongoose connection to include the replica set parameter:

```javascript
mongoose.connect("mongodb://127.0.0.1:27017/mydb?replicaSet=rs0");
```

For MongoDB Compass, use:

```plaintext
mongodb://127.0.0.1:27017/?replicaSet=rs0
```

* * *

## Alternative Method: Command Line Approach

If you prefer not to modify the config file or need a temporary solution, you can start MongoDB manually with replica set enabled:

### Step 1: Stop the MongoDB Service

```bash
net stop MongoDB
```

### Step 2: Start MongoDB with Replica Set Flag

Open **Command Prompt as Administrator** and run:

```bash
mongod --dbpath "C:\Program Files\MongoDB\Server\7.0\data" --replSet rs0
```

Adjust the `--dbpath` if your data folder is in a different location.

### Step 3: Initialize the Replica Set

Open another Command Prompt and run:

```bash
mongosh
```

Then initialize:

```javascript
rs.initiate();
```

**Note**: With this approach, you need to run the `mongod` command each time you want to start MongoDB. For a permanent solution, use the config file method above.

* * *

## Using Transactions in Mongoose

Now transactions will work properly:

```javascript
const session = await mongoose.startSession();

await session.withTransaction(async () => {
  await User.create([{ name: "Rakib" }], { session });
  await Wallet.updateOne(
    { userId: 1 },
    { $inc: { balance: -10 } },
    { session },
  );
});

session.endSession();
```

* * *

## Troubleshooting

### Connection Timeout After Configuration

If MongoDB Compass or your application can't connect after making configuration changes:

1.  **Verify MongoDB is running**:
    
    ```bash
    netstat -ano | findstr 27017
    ```
    
    You should see: `TCP 127.0.0.1:27017 LISTENING`
    
2.  **Check the MongoDB log file** at `C:\Program Files\MongoDB\Server\7.0\log\mongod.log` for errors
    
3.  **Ensure replica set is initialized**:
    
    *   Connect with `mongosh mongodb://127.0.0.1:27017`
        
    *   Run `rs.initiate()` if not already done
        
    *   Check `rs.status()` to confirm `"stateStr": "PRIMARY"`
        

### Common Configuration Errors

*   **YAML syntax errors**: Use spaces (not tabs) for indentation in `mongod.cfg`
    
*   **Missing replica set initialization**: The warning `Collection [local.oplog.rs] not found` appears until you run `rs.initiate()`
    
*   **Wrong connection string**: Always include `?replicaSet=rs0` when connecting to a replica set
    

### If Service Won't Start

1.  Check `mongod.cfg` syntax (especially spacing in the YAML)
    
2.  Review the last lines in the MongoDB log file
    
3.  Ensure file paths in the config match your installation
    

* * *

## Summary

| Issue | Solution |
| --- | --- |
| Standalone MongoDB | Doesn't support transactions |
| Fix | Enable single-node replica set |
| Config | Add `replication: replSetName: rs0` to `mongod.cfg` |
| Initialize | Run `rs.initiate()` in mongosh |
| Connection | Add `?replicaSet=rs0` to connection string |

✅ After completing these steps, MongoDB transactions will work perfectly in your Node.js application.
