【发布时间】:2022-02-11 22:39:31
【问题描述】:
我是 JavaScript 新手,目前正在使用 node.js 学习 mongoDB。 Bellow 的代码在回调函数中,但我想使用 async 连接到 mongoDB 数据库并使用 try 和 catch 等待。
const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/selfdb");
mongoose.connection
.once("open", () => {
console.log("connection has been made!");
})
.on("error", (error) => {
console.log("connection error:", error);
});
我试过这样做:
const mongoose = require("mongoose");
async function main() {
const uri = "mongodb://localhost/selfdb";
const client = new mongoose(uri);
try {
await client.connect();
console.log("connection has been made!");
} catch (e) {
client.error(e);
} finally {
await client.close();
}
}
main().catch(console.error);
但我收到以下错误:
TypeError: mongoose 不是构造函数
我怎样才能以正确的方式做到这一点? 我犯了什么愚蠢的错误吗?
【问题讨论】:
标签: node.js mongodb async-await callback