I tried to connect to mongodb atlas that i've just created, but I got this error :
{ MongoError: failed to connect to server [mongodbarcode-tt80c.mongodb.net:27017] on first connect [MongoError: getaddrinfo ENOTFOUND mongodbarcode-tt80c.mongodb.net mongodbarcode-tt80c.mongodb.net:27017]
here's my code :
import mongoose from 'mongoose';
import config from '../config/index';
mongoose.Promise = global.Promise;
const connectToDb = async () => {
try {
await mongoose.connect(mongodb://test:fakepass#mongodbarcode-tt80c.mongodb.net/test?retryWrites=true, { useMongoClient: true });
console.log('Connected to mongo!!!');
}
catch (err) {
console.log(err);
// logger.error('Could not connect to MongoDB');
}
}
export default connectToDb;
also, i added a whitelist IP address :0.0.0.0/0 to connect from everywhere, but i always get the same error, any suggestions please ?
Related
Connection error on tring to connect to mssql 2019 db running in a docker container
const sql = require('mssql');
async function connectdb() {
const config = {
user: 'SA',
password: 'password',
server: 'container_name',
database: 'database_name',
};
try{
const connection = await sql.connect(config);
console.log('Connected to the database!');
}
catch(err){
console.error('Error connecting to the database:', err)
}
}
connectdb()
Expected behaviour: "Connected to db" logged to the console.
Actual behaviour: "Error connecting to the database: ConnectionError: Failed to connect to container_name:1433 - getaddrinfo EAI_AGAIN container_name" logged to the console
So when I run my app in deployment, with the backend connecting to MongoDB using MongoClient as follow:
import { MongoClient } from 'mongodb'
const url = process.env.MONGODB_URI
MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true },(err, db)=>{
console.log(url)
db.close()
})
everything works fine. But if I change it into
import mongoose from 'mongoose'
mongoose.Promise = global.Promise
mongoose.connect(url, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true })
mongoose.connection.on('error', () => {
throw new Error(`unable to connect to database: ${url}`)
})
it gives the following error:
webpack://HappyHourWeb/./server/server.js?:29
throw new Error(`unable to connect to database: ${_config_config__WEBPACK_IMPORTED_MODULE_0__["default"].mongoUri}`)
^
Error: unable to connect to database: my_database_url,
at NativeConnection.eval (webpack://HappyHourWeb/./server/server.js?:29:9)
at NativeConnection.emit (node:events:390:28)
at /Users/Hieudo/Documents/Project/HappyHourWeb/node_modules/mongoose/lib/connection.js:807:30
at processTicksAndRejections (node:internal/process/task_queues:78:11)
Any help is greatly appreciated!
According to various sources, including MongoDB Connection String URI reference, Mongoose connection docs (Ctrl+F and search for srv to jump to the right topic) and the most upvoted answer on this question on SO, you should handle standard URIs and DNS URIs differently.
Mongoose accepts a dbName option that is
[...]useful if you are unable to specify a default database in the connection string like with some mongodb+srv syntax connections.
The fact that the native MongoDB driver handles it automatically doesn't necessarily means that Mongoose will. Try separating the DB name from the URI and pass it as the second argument when connecting with Mongoose.
Also, that part of your code :
mongoose.connection.on('error', () => {
throw new Error(`unable to connect to database: ${url}`)
})
doesn't check for connection errors, it emits an event if an error is encountered after the initial connection has been made.
As Joe pointed out in the comments, you should handle both the initial connection errors AND errors that may come after it, either with the try/catch syntax or the .catch callback. More info in the docs.
I am trying to connect to cloud mongo db using mongoose with the connection string
const mongoose = require("mongoose");
mongoose.connect(
"mongodb+srv://<user>:<pass>#<cluster>/<db>?retryWrites=true&w=majority", {
useNewUrlParser: true,
useUnifiedTopology: true
}
).then(res => {
console.log("successful" + res);
})
.catch(err => {
console.log("connection error:", err);
})
module.exports = mongoose;
This works fine on my local machine but when I upload and run it on my production server it doesn't connect.
I have to set it to allow connections from all IPs and I have also add my server IP to it but still it shows me the same error
I am trying to connect a MongoDB atlas instance to a nodejs/express server :
const mongoose = require("mongoose");
const dbURI =
"mongodb+srv://(url copied from atlas connect)";
const options = {
useNewUrlParser: true,
dbName: "data"
};
mongoose.connect(dbURI, options).then(
() => {
console.log("Database connection established!");
},
err => {
console.log("Error connecting Database instance due to: ", err);
}
);
But I keep get the following error:
MongoNetworkError: connection 5 to cluster ... 27017 closes at TLSSocket. ...
How can I fix this?
Resolved -- Check IP whitelist!
My connection code is entered below. I'm trying to connect to the MongoDB atlas free shared cluster and I keep getting an error saying cannot connect to the server in the first time.
const express = require("express");
const app = express();
const morgan = require("morgan");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
mongoose.Promise = require('bluebird');
const productRoutes = require("./api/routes/products");
const orderRoutes = require("./api/routes/orders");
mongoose.connect(
"mongodb://username:password6#cluster0-shard-00-00-3xdjv.mongodb.net:27017,cluster0-shard-00-01-3xdjv.mongodb.net:27017,cluster0-shard-00-02-3xdjv.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin",
{
useMongoClient: true
}
) .then(() => { // if all is ok we will be here
return server.start();
})
.catch(err => { // we will not be here...
console.error('App starting error:', err.stack);
process.exit(1);
});
Can someone explain why I keep getting this error:
App starting error:
MongoError: failed to connect to server [cluster0-shard-00-00-3xdjv.mongodb.net:27017] on first connect
[MongoError: getaddrinfo EAI_AGAIN
cluster0-shard-00-00-3xdjv.mongodb.net:27017].....
I had the same problem before I realized that I had set up a network access rule allowing only connections from a certain IP. After deleting that restriction and adding a new rule for allowing all connections from anywhere, the problem was gone
My datasource config is as follows:
"mongodb-atlas": {
"url": "mongodb+srv://dbuser:PaSsWOrd#cluster0-oxxxb.gcp.mongodb.net/test?retryWrites=true&w=majority&authSource=admin",
"name": "mongodb-atlas",
"connector": "mongodb",
"database": "admin"
}