【问题标题】:how to use async and await to connect to mongoDB database?如何使用 async 和 await 连接到 mongoDB 数据库?
【发布时间】: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


    【解决方案1】:

    我相信更好的连接方式是这样

    const mongoose = require('mongoose')
    
    const connectDB = async () => {
      try {
        const conn = await mongoose.connect(process.env.MONGO_URI)
        console.log(`MongoDB Connected: ${conn.connection.host}`)
      } 
      catch (error) {
        console.log(error)
        process.exit(1)
      }
    }
    
    module.exports = connectDB
    

    Mongo URI 在 .env 文件中,但您可以将其替换为连接字符串(但在 .env 文件中更安全)

    然后在 server.js 或 index.js 中(入口文件)

    const connectDB = require('path_to_file')
    
    connectDB()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-06
      • 1970-01-01
      • 2022-01-11
      • 2019-12-19
      • 2022-07-18
      • 1970-01-01
      • 2021-09-12
      • 1970-01-01
      相关资源
      最近更新 更多