无法使用错误UnhandledPromiseRejectionWarning连接到MongoDB

问题描述 投票:0回答:1

我正在使用Visual Studio Code。

我试图连接到MongoDB数据库来存储值,但后来我收到一个错误:UnHandledPromiseRejection

error => UnhandledPromiseRejectionWarning:错误:连接ETIMEDOUT 13.234.193.81:27017

这是我用来连接MongoDB的代码:

mongoose.connect('mongodb://node-shop:'+ process.env.MONGO_ATLAS_PW +'@node-rest-shop-shard-00-00-ylfa8.mongodb.net:27017,node-rest-shop-shard-00-01-ylfa8.mongodb.net:27017,node-rest-shop-shard-00-02-ylfa8.mongodb.net:27017/test?ssl=true&replicaSet=node-rest-shop-shard-0&authSource=admin&retryWrites=true', {
    useNewUrlParser: true 
});
node.js mongodb mongoose
1个回答
0
投票

你使用的方式返回一个承诺。你必须通过回调来处理它。如果你还没有使用第二种方式,如下所示。 Async / Await主体将起作用

1.
    mongoose.connect(uri, options, function(error) {
      // Check error in initial connection. There is no 2nd param to the callback.
    });

2.  
    // Or using promises
    mongoose.connect(uri, options).then(
      () => { /** ready to use. The `mongoose.connect()` promise resolves to undefined. */ },
      err => { /** handle initial connection error */ }
    );
© www.soinside.com 2019 - 2024. All rights reserved.