MongoError: Pool was force destroyed

My project is in nodejs platform. I got this error and server destroy. Error is occur in my CRON job function.

Hi @Zil_D,
I believe that the connection is being closed because you may have incorrectly scoped your MongoClient instance or running async functions and might be closing the connection before those functions return.

If that’s not the case, can you please provide the following details in order to help us reproduce this issue:

  • The version of Node.js installed on your machine
  • The version of MongoDB Driver you are using in your project
  • A minimal code snippet that reproduces this connection error

Also, take a look at this guide to learn how to connect your Node.js server to the cluster.

If you have any doubts, please feel free to reach out to us.

Thanks and Regards.
Sourabh Bagrecha,
MongoDB

Hi @SourabhBagrecha ,
Thanks for your reply.

@SourabhBagrecha ,
I’m using nodejs version 14 & moongoose as ODM. Let me share connection code snippet.

// Connection setup

mongoose.connect(process.env.DB_URL, {
  useCreateIndex: true,
  useNewUrlParser: true,
  useFindAndModify: false,
  ignoreUndefined: true,
});

const connection = mongoose.connection;
app.use("*", express.static(drname));
connection.once("open", function () {
  console.log("MongoDB database connection established successfully");
});
server.listen(3002, () => {
  console.log("Started your server on PORT 3002");
});

Also DB is of mongoDB altas.

One more thing @SourabhBagrecha , My co-worker has used async/await for DB operations in the js map function in cron job. I know this is apart from mongoDB but just informing you if you have idea.

Hi @Zil_D,
Thanks for sharing that. Can you help us by providing some the following details:

  • mongoose version
  • I believe the connection code you shared is creating a server, but you mentioned that your issue is about a cron job. Could you post the code that’s causing the error instead?

Also, can you elaborate more on this?

If you have any doubts, please feel free to reach out to us.

Thanks and Regards.
Sourabh Bagrecha,
MongoDB

Hi @SourabhBagrecha ,

  1. “mongoose”: “^5.10.0”
  2. Sharing CRON job function code below:
const refund = async () => {
  try {
    let sessions = await Session.find({
      type: "PUBLISHED",
    });
    sessions.map(async (session) => {
      await refundOrder(session._id);
      await saveHistory(session._id);
      await Session.findByIdAndUpdate(session._id, {
        students_ids: [],
      });
    });
  } catch (error) {
    logger.log(error)
    console.log("Error in CRON", error);
  }
};

I have updated this map function into for of loop but verifying whether this is causing an error or not.