我正在用mongo和node构建我的第一个测试API REST
我正在打开与数据库的连接,它工作正常…但我不能处理这个错误案例。尽管我写了一个错误的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);
});
有人能告诉我我做错了什么吗?谢谢