javascript - Mongoose 连接无法处理错误

标签 javascript node.js mongodb mongoose

我正在使用 Mongo 和 Node 构建我的第一个测试 API Rest

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

例如:

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 方法,用于事件委托(delegate)任务),但它不起作用要么,因为即使数据库名称再次错误,“connected”事件总是会触发。

// 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);
}); 

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

最佳答案

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

来自the reference

/database Optional. The name of the database to authenticate if the connection string includes authentication credentials in the form of username:password@. If /database is not specified and the connection string includes credentials, the driver will authenticate to the admin database.

关于javascript - Mongoose 连接无法处理错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50592789/

相关文章:

json - Spring boot 启动器数据休息,@Notnull 约束不起作用

java - Spring Data for MongoDB 聚合查询

node.js - 从 node.js session 获取信息与从数据库获取信息

javascript - Firebug 不会加载 JavaScript 文件或在断点处停止执行

javascript - 类模块的声明文件 (TypeScript)

javascript - Action Method 可以从 ajax post 获取参数中的双值

mysql - Node js : association not working in sails js version 1

javascript - 在 Cloud Foundry Node.js 上运行子进程

javascript - 创建一个函数来进行乘法运算

javascript - PrettyPhoto 在模态窗口中加载时卡住