Code Hangs on Connection

Could someone help with this problem?
I am using MongoDB version 6. The driver version is 5.1
MongoDB is running as a service on Windows 10.
When I run the following simple code to connect to the database the code hangs.
The fruitsDB has already been set up and has one collection called ‘fruits’
I will show you the code and the appropriate portion of the logs.
Thanking you

app.js

console.log('Starting MongoDB connection...');
const { MongoClient } = require('mongodb');

// Connection URL with the database name
const url = 'mongodb://127.0.0.1:27017/fruitsDB';

// Create a new MongoClient
const client = new MongoClient(url, { useUnifiedTopology: true });

setTimeout(() => {
	// Use connect method to connect to the Server
	client.connect(function (err) {
		if (err) {
			console.log(err);
			return;
		}

		console.log("Connected successfully to server");

		const db = client.db('fruitsDB');

		// Perform further operations on the database here

	});
}, 2000); // Wait 5 seconds before connecting

Here are the logs:

{"t":{"$date":"2023-03-30T09:42:31.973+02:00"},"s":"I",  "c":"NETWORK",  "id":22943,   "ctx":"listener","msg":"Connection accepted","attr":{"remote":"127.0.0.1:63528","uuid":"1593aa60-b0b1-46d3-b011-47e8ec2db558","connectionId":34,"connectionCount":1}}
{"t":{"$date":"2023-03-30T09:42:31.979+02:00"},"s":"I",  "c":"NETWORK",  "id":51800,   "ctx":"conn34","msg":"client metadata","attr":{"remote":"127.0.0.1:63528","client":"conn34","doc":{"driver":{"name":"nodejs","version":"5.1.0"},"os":{"type":"Windows_NT","name":"win32","architecture":"x64","version":"10.0.19045"},"platform":"Node.js v18.15.0, LE (unified)|Node.js v18.15.0, LE (unified)"}}}

Hello @Greg_Guy ,

Welcome to The MongoDB Community Forums! :wave:

Based on the provided code and logs, it seems that the connection to MongoDB is being established successfully and there are no errors reported. I think your code looks like in hang state because the connection was never closed.

However, I noticed that you are not using Promises and client.close() statement to connect or to close the already opened connection. Below blobs are from documentation regarding Promises

Promises

A Promise is an object returned by the asynchronous method call that allows you to access information on the eventual success or failure of the operation that they wrap. The Promise is in the Pending state if the operation is still running, Fulfilled if the operation completed successfully, and Rejected if the operation threw an exception. For more information on Promises and related terminology, see the MDN documentation on Promises.

Await

If you are using async functions, you can use the await operator on a Promise to pause further execution until the Promise reaches either the Fulfilled or Rejected state and returns. Since the await operator waits for the resolution of the Promise, you can use it in place of Promise chaining to sequentially execute your logic. For additional information, see the MDN documentation on await.

Below is an example on how you can use such syntax and you may update the same as per your requirements

console.log('Starting MongoDB connection...');
const { MongoClient } = require('mongodb');

// Connection URL with the database name
const url = 'mongodb://127.0.0.1:27017/fruitsDB';

// Create a new MongoClient
const client = new MongoClient(url, { useUnifiedTopology: true });

async function main() {
	try {
		// Use connect method to connect to the Server
		await client.connect();
		console.log("Connected successfully to server");

		const db = client.db('fruitsDB');

		// Perform further operations on the database here

	} catch (err) {
		console.log(err);
	} finally {
		await client.close();
	}
}

main();

This code uses async/await to wait for the client.connect() method to resolve before proceeding with the rest of the code. The try/catch block is used to catch any errors that may occur, and the finally block is used to ensure that the client.close() method is called, regardless of whether an error occurred or not.

I hope this helps resolve the issue with your code hanging.

Regards,
Tarun

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.