Search code examples
mongoose

Unable to get MongoClient instance from Mongoose connection


This api document says that client property is MongoClient instance - https://mongoosejs.com/docs/api/connection.html#Connection()

When I run the following code, I get error when trying to get a database name using the clent - something bad happened in dbconnect: TypeError: Cannot read properties of undefined (reading 'db'). It is because client is undefined.

const connection = await mongoose.connect("mongodb://0.0.0.0:27017");
  console.log('connected to Mongo');
    
  const client = connection.client; //SHOULD GET MONGO CLIENT
    
  try {
    const db = client.db("admin");
    console.log(`connected to database ${db.databaseName}`);
    const collections = await db.collections();
    collections.forEach(c => {console.log(`got collection ${c.collectionName}`)})
  } catch(exception) {
    console.log(`something bad happened in dbconnect: ${exception}`); //ERROR 
  } finally {
    console.log("closing database connection");
    connection.disconnect();
  }

What am I missing?


Solution

  • I think you want connection.connections[0].client like:

    const mongoose = require('mongoose');
    
    (async () => {
      try {
        const connection = await mongoose.connect("mongodb://0.0.0.0:27017");
    
        const client = connection.connections[0].client;
    
        const db = client.db("admin");
        const collections = await db.collections();
        collections.forEach(c => {
          // do something
        });
      } catch (exception) {
    
      } finally {
        mongoose.disconnect();
      }
    })();