Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 使用异步/await-NodeJS的mongodb连接_Node.js_Mongodb_Mongoose_Async Await_Mongodb Atlas - Fatal编程技术网

Node.js 使用异步/await-NodeJS的mongodb连接

Node.js 使用异步/await-NodeJS的mongodb连接,node.js,mongodb,mongoose,async-await,mongodb-atlas,Node.js,Mongodb,Mongoose,Async Await,Mongodb Atlas,我通常使用.then()进行MongoDB连接,因为在过去,我是通过文档学习如何进行连接的 使用async wait这是正确的方法吗? const express = require('express'); const mongoose = require('mongoose'); const app = express(); //DB Connection getConnection = async () => { try { await mongoose.connect(

我通常使用
.then()
进行MongoDB连接,因为在过去,我是通过文档学习如何进行连接的

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

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()
查找错误消息。非常感谢!!您知道使用async await是否比使用.then()有任何缺点吗?我不认为有任何缺点。您应该注意这一点:另外,您还可以阅读一些好的博客,以了解有关使用then或使用async WAIT实现承诺的更多详细信息。