node.js - 类型错误: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}`)
})
})
解决方案
根据文档,客户端只是您的数据库实例:
// 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");
推荐阅读
- jquery - Jquery 控制台错误 - 无法读取未定义的属性“调用”
- php - 具有数据属性的打开模式无法正常工作
- java - 在 LANDSCAPE 或 PORTRAIT 中调整视频视图的尺寸
- mesh - GMSH 3D 表面网格
- html - 如何将 Font Awesome 图标右对齐?
- html - 引导 4 个彼此相邻的项目
- python - 基于字符串值执行 <、>、==、<= 或 >= 操作的 Pythonic 方式?
- reactjs - 为什么 mapStateToProps 不更新我的组件的道具?
- javascript - JavaScript:使用子类更改默认函数?
- wordpress - 替换 WordPress 默认搜索字段中的占位符文本