skip to Main Content

This is the primary program of node.js to connect MongoDB. Copied from the internet because my actual code not working, so I am trying this one. This raises the same issue.

Problem with this code or in my local machine. When I ran the program, it got stuck or in any loop, and after a few minutes, it shows timeout, without any further detailed error message.

const MongoClient = require("mongodb").MongoClient;


// Connection URL
const url = "mongodb://localhost:27017";

// Database Name
const dbName = "myproject";

// Create a new MongoClient
const client = new MongoClient(url);

// Use connect method to connect to the Server
client.connect(function (err) {

console.log("Connected successfully to server");
const db = client.db(dbName);
client.close();
});

Try to connect with atlas or local mongoDB compass.

2

Answers


  1. Please try the below code for the DB connection.

    var mongoose = require("mongoose");
    try {
      mongoose.connect(
        "mongodb://localhost:27017/myproject",
        {
          useNewUrlParser: true,
          useFindAndModify: false,
          useUnifiedTopology: true,
          useCreateIndex: true,
        },
        function (err, db) {
          if (err) {
            console.log("MongoDB Database Connection Error", err);
          } else {
            console.log("MongoDB Connection Done!!");
          }
        }
      );
    } catch (e) {
      console.log("🚀 ~ file: mongodb.js ~ line 24 ~ e", e);
    }
    
    Login or Signup to reply.
  2. Check this code

    const mongoose = require('mongoose');
    
    connectionUri = `mongodb://${config.get('server:mongodb:username')}:${config.get('server:mongodb:password')}@${config.get('server:mongodb:host')}:${config.get('server:mongodb:port')}/${config.get('server:mongodb:name')}?authSource=admin`;
    mongoose.connect(connectionUri, { useNewUrlParser: true });
    

    replace with your username and password

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search