【问题标题】:mongodb connection using async/await - NodeJS使用 async/await 的 mongodb 连接 - NodeJS
【发布时间】:2020-01-06 03:03:51
【问题描述】:

我通常使用.then() 进行 MongoDB 连接,因为这就是我在过去根据文档学习如何操作的方法。

这是使用async await 的正确方法吗?

const express = require('express');
const mongoose = require('mongoose');
const app = express();

//DB Connection
getConnection = async () => {
  try {
    await mongoose.connect(
      'mongodb+srv://XXXX:XXXX@porellasmap-cluster-tgcab.mongodb.net/porellasmap',
      { useCreateIndex: true, useNewUrlParser: true }
    );
    console.log('Connection to DB Successful');
  } catch (err) {
    console.log('Connection to DB Failed');
  }
};

getConnection();

//More code

仅供参考:连接有效

【问题讨论】:

  • 你的做法绝对正确。
  • 你做对了。
  • 使用.then() 表示成功,使用.error() 以找出错误消息。

标签: node.js mongodb mongoose async-await mongodb-atlas


【解决方案1】:

您做的绝对正确,请参阅下面的官方 mongoose 文档:

更多详情: https://mongoosejs.com/docs/connections.html

【讨论】:

  • 非常感谢!!你知道做 async await 是否比使用 .then() 有任何缺点吗?
  • 我不认为有任何缺点。你应该看看这个:youtu.be/ho5PnBOoacw 还有一些不错的博客你可以阅读以找到更多关于使用 then 或在 promise 上使用 async-await 的 Promises 的详细信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-19
  • 2021-10-05
  • 2021-06-15
  • 1970-01-01
  • 2018-09-10
相关资源
最近更新 更多