Home > Software engineering >  NodeJS Mongoose | Why Transaction Timeout?
NodeJS Mongoose | Why Transaction Timeout?

Time:11-09

I want to use transactions and followed the mongoose manual but my code does not work. Here is a minimal non working example:

const mongoose = require('mongoose');

const Customer = mongoose.model('Customer', new mongoose.Schema({ firstName: { type: String } }));

const start = async () => {
  try {
    const db = await mongoose.createConnection("mongodb://localhost:27017/transactions");
    const session = await db.startSession();

    await session.withTransaction(() => {
      return Customer.create([{ firstName: "peter" }], { session: session });
    });
  }
  catch (error) {
    console.error(error);
  }
};

start();

I get the following error:

MongooseError: Operation `customers.insertOne()` buffering timed out after 10000ms
    at Timeout.<anonymous> (C:\Users\joshua\Documents\Business\transactionMongoDBStudy\transactionMongoDb\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:149:23)
    at listOnTimeout (internal/timers.js:557:17)
    at processTimers (internal/timers.js:500:7)

I am doing it the same as described here: https://mongoosejs.com/docs/transactions.html but its not working and i don't know why.

CodePudding user response:

I have experienced the same error. And I solved it by using mongoose.connect function instead of mongoose.createConnection function.You can change your db connection code with something like that.

const db = await mongoose.connect("mongodb://localhost:27017/transactions");

CodePudding user response:

SOLUTION You have to use MongoDB with replica. I simply used the the Atlas hosted dedicaded Server and it works.

  • Related