类型错误:conn.db 不是函数

问题描述

当我尝试连接到我的 mongodb 数据库中的集合时出现此错误: 类型错误:conn.db 不是函数

PS:我使用的是 4.4.6 版

感谢您的帮助!

export default class OfferingDAO {
static async injectDB(conn){
    if(offerings){
        return;
    }
    try { 
        offerings = await conn.db(process.env.NS).collection("Offering");
    }
    catch(e){
        console.error(`Unable to establish a collection handle in OfferingDAO: ${e}`);
    }
}

这是我连接到mongodb的代码

await mongoose.connect(process.env.URI,{
  useNewUrlParser: true,useUnifiedTopology: true,useFindAndModify: false,useCreateIndex: true
})
.then(async (client) => {
  await OfferingDAO.injectDB(client);
  app.listen(port,() => {
      console.log(`listening on port ${port}`)
  }) 
})

解决方法

根据文档,客户端只是您的数据库实例:

// Using `mongoose.connect`...
var promise = mongoose.connect('mongodb://localhost/myapp',{
  useMongoClient: true,/* other options */
});
promise.then(function(db) {
  /* Use `db`,for instance `db.model()`
});

所以如果你的代码更新为:

offerings = await conn.collection("Offering");