Hello @Greg_Guy ,
Welcome to The MongoDB Community Forums!
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
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 theawait
operator on a Promise to pause further execution until the Promise reaches either the Fulfilled or Rejected state and returns. Since theawait
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