猫鼬未连接到MongoDB服务器
确保密码和用户名正确
const mongoose = require('mongoose')
mongoose.Promise = global.Promise
const uri ="mongodb+srv://halbr:password@cluster0-t2noa.mongodb.net/test?retryWrites=true&w=majority"
mongoose.connect(uri).then(
() => {
console.log('Connect to Mongo');
},
err => {
console.log("Error connecting to Mongo:")
console.log(err);
}
);
module.exports = mongoose.connection
答案 0 :(得分:0)
可以请尝试以下示例:
const mongoose = require('mongoose')
mongoose.Promise = global.Promise
async function myDbConnection() {
const url = 'mongodb+srv://halbr:password@cluster0-t2noa.mongodb.net/test?retryWrites=true&w=majority';
try {
let connectionPromise = await mongoose.connect(url, { useNewUrlParser: true });
if (mongoose.connection) {
console.log('Connected Successfully')
global.connectionPromise = connectionPromise;
} else { global.connectionPromise = null;
console.log('not connected to DB') }
return connectionPromise;
} catch (error) {
console.log('Error connecting to DB ::', error);
}
}
module.exports = myDbConnection();
答案 1 :(得分:0)
请确认您已在IP白名单中添加了公共IP,为了进行测试,您可以添加通配符。 0.0.0.0/0
,如果可以,您可以尝试通过命令行连接到db,但该连接不起作用,我建议添加具有root角色的新用户,然后再次检查连接。
use admin
db.createUser(
{
user: "admin",
pwd: "password",
roles: [ { role: "root", db: "admin" } ]
}
);
exit;