【发布时间】: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