我正在使用 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 中传递用户名和密码时才相关
语法。
/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/