首页 文章

MongoDB - 未连接到数据库并且.catch函数出错

提问于
浏览
0

The code below is what is wrong and it runs up until it gets to the .catch function with Mongo DB. And I can't figure out what is wrong. If i remove the catch and let it error it shall come up with this error -

(node:72993)UnhandledPromiseRejectionWarning:未处理的promise拒绝(拒绝ID:1):MongoError:第一次连接时无法连接到服务器[localhost:27017] [MongoError:connect ECONNREFUSED 127.0.0.1:27017]

//Dependicies
var express = require("express");
var mongoose = require("mongoose");
var bodyParser = require("body-parser");
var routes = require('./routes/route');
var app = express();


//MongoDB
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/filmo', { useMongoClient: true }, function () {

console.log("Connected to Database")

}).catch(function () {
  console.log("Not Connected to Database ERROR!");


});


//Routes Listed
app.use('/', routes);


//Start Server
const defaultPortNumber = 8080
const port = process.env.PORT || defaultPortNumber

app.listen(port, err => console.log(err || `API is Running on port ${port}.`))

添加了代码以通过此链接查看错误实际上在说什么 - How do I find out where an unhandled promise rejection occured?

And Error now says - MongoError:首次连接时无法连接到服务器[localhost:27017] [MongoError:connect ECONNREFUSED 127.0.0.1:27017]

1 回答

  • 0

    您在普通回调和承诺处理之间使用了一些奇怪的组合 . 当您无法连接时,这是您的问题,您会得到:

    C:\test> node app
    API is Running on port 8080.
    Connected to Database
    Not Connected to Database ERROR!
    

    因为调用了回调函数和catch函数 .

    如果你想处理从 connect 返回的承诺,你应该像这样使用 then()catch()

    mongoose.connect('mongodb://localhost/filmo', { useMongoClient: true }).then(() => {
        console.log("Connected to Database");
    }).catch((err) => {
        console.log("Not Connected to Database ERROR! ", err);
    });
    

    现在,如果连接失败,它将选择 then 函数或 catch 函数 .

    实际错误是 ECONNREFUSED . 这意味着您的应用程序无法连接到数据库 . 确保 mongod 正在运行 . 如果它不是这样的情况你将得到完全错误消息然后确保端口mongod正在运行是27017,因为如果你没有在连接url中提供它,那么这是默认端口 .

    最后,如果您缺少 catch 函数或者您没有在普通回调中处理错误,则会显示UnhandledPromiseRejectionWarning消息 .

    例如 . 普通回调:

    这会给你UnhandledPromiseRejectionWarning:

    mongoose.connect('mongodb://localhost/filmo', { useMongoClient: true }, () => {
        console.log("Connected to Database");
    })
    

    这不会:

    mongoose.connect('mongodb://localhost/filmo', { useMongoClient: true }, (err) => {
        if (err) throw err;
        console.log("Connected to Database");
    })
    

相关问题