首页 > 解决方案 > 类型错误:conn.db 不是函数

问题描述

当我尝试连接到我的 mongodb 数据库中的集合时出现此错误:TypeError: conn.db is not a function

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}`)
  }) 
})

标签: node.jsmongodbmern

解决方案


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

// 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");

推荐阅读