mongoose连接无法处理错误

时间:2018-05-29 20:54:52

标签: javascript node.js mongodb mongoose

我正在使用Mongo和Node

构建我的第一个测试API休息

我正在打开与数据库的连接,它工作正常......但是我无法处理错误情况。尽管我写了一个错误的URI,但它仍然是一个成功的连接。尝试过承诺,回调和事件,但没有任何作用:

例如:

const mongoose=require('mongoose');
mongoose.Promise = global.Promise;
const express=require('express');
const bodyParser=require('body-parser');
const portApp=1300;

const app=express();

app.listen(portApp,'localhost',()=>{
    console.log(`server works fine at ${portApp}`);


    mongoose.connect('mongodb://localhost:27017/RIGHTdbname')
    .then((res)=>
    {
        console.log(`successful connection to BBDD`);
       //console.log(res);

    })
    .catch((error)=>{

        console.log("error"+error.message);
    });

});

没关系,它会抛出“成功连接到BBDD”......问题是,当我写错了数据库名称时,它会抛出相同的内容!

我也尝试过回调。像建议的here

 mongoose.connect('mongodb://localhost:27017/WRONGdbname',function(err){

    if(err)
    {
        throw err;
    }
});

并尝试使用这些事件(取自here,我实际上不理解,过去只使用.on()jquery方法,用于事件委派任务),但它没有也可以工作,因为即使数据库名称错误,也会一直触发“已连接”事件。

// When successfully connected
mongoose.connection.on('connected', function () {  
  console.log('Mongoose default connection opened);
}); 

// If the connection throws an error
mongoose.connection.on('error',function (err) {  
  console.log('Mongoose default connection error: ' + err);
}); 

有人可以解释一下我做错了什么吗?感谢

1 个答案:

答案 0 :(得分:1)

Mongo连接字符串中的“数据库”用于身份验证,仅当您使用mongodb://user:pass@host:port/database语法在URL中传递用户名和密码时才相关。

来自the reference

  

/ database可选。如果连接字符串包含username:password @形式的身份验证凭据,则要验证的数据库的名称。如果未指定/ database且连接字符串包含凭据,则驱动程序将对admin数据库进行身份验证。