无法从Mongoose连接获取MongoClient示例

wh6knrhe  于 2023-08-06  发布在  Go
关注(0)|答案(1)|浏览(101)

这个api文档说client属性是MongoClient示例-https://mongoosejs.com/docs/api/connection.html#Connection()
当我运行下面的代码时,我在尝试使用clent -something bad happened in dbconnect: TypeError: Cannot read properties of undefined (reading 'db')获取数据库名称时出错。这是因为clientundefined

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();
  }

字符串
我错过了什么?

6rqinv9w

6rqinv9w1#

我想你想要connection.connections[0].client像这样:

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();
  }
})();

字符串

相关问题