Problem connecting to MongoDB Atlas cluster with mongoose (NodeJS) - node.js

I've been struggling to connect to my mongodb atlas cluster through mongoose. I'm still fairly new to nodejs, but after searching around all I could find was to set the flag to
useNewUrlParser: true and my own compiler threw a warning for me to add useUnifiedTopology: true. However it keeps getting caught as an error. Thanks for any advice or direction
Update: when outputting err, i get
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }
going to dig into this now
//THIS IS PART OF .ENV
ATLAS_URI=mongodb+srv://myusername:mypw#cluster(:idhere).mongodb.net/test?retryWrites=true&w=majority
//THIS IS PART OF SERVER.JS
const express = require('express');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const uri = process.env.ATLAS_URI;
// console.log('URI = "' + uri + '"'); //outputs correct URI
//without these two flags, get deprecated warning
mongoose.connect( uri, { useNewUrlParser: true, useUnifiedTopology: true })
.catch(err => {
console.log('URI error'); //still goes into here
});

Related

Mongoose parser error while connecting with mongoDB atlas

while trying to connect with my mongoDB atlas using mongoose connect method in node js I'm getting below mentioned parser error, I've checked my DB credentials and there are no special characters (:, /, ?, #, [], #) present in it.
Error:
MongoParseError: URI malformed, cannot be parsed
Code:
const mongoose = require('mongoose');
const DB = process.env.DB.replace('<password>', process.env.DB_PASSWORD);
mongoose
.connect(DB, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
})
.then((con) => {
console.log(con.connections);
console.log('DB connection successful!');
});

Connect to MongoDB cluster

Hi I am trying to connect MongoDB and I got an error. I worked on connecting DB by "connect with the MongoDB shell", but this time I want to connect with the "connect your application" option.
When I hit mongosh in the embedded terminal in my mac, below was returned.
Connecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.2.2
Using MongoDB: 5.0.6
Using Mongosh: 1.2.2
...
...
...
test>
Because I am new to MongoDB, I don't even know if it's correctly working or not. Also, I wanna connect by coding. That's why I am asking here. Below are some parts of my code in an app I have been working on.
Thanks for your time for dedication here. So appreciate it.
// this is db.js file in a config folder.
const mongoose = require('mongoose')
// It must be a promise function to connect db
const connectDB = async () => {
try {
console.log(`try`)
const conn = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
dbName: 'expense2'
});
console.log(`MongoDB Connected: ${conn.connection.host}`.syan.underline.bold)
} catch (error) {
console.log(`Error: ${error.message}`.red)
process.exit(1);
}
}
module.exports = connectDB;
/*
Here is the error happened
Error: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/
[nodemon] app crashed - waiting for file changes before starting...
*/
config.env in the config folder as well.
NODE_ENV = development;
PORT=5000
MONGO_URI=mongodb+srv://mongo:mongo#cluster0.8tjjn.mongodb.net/expense2?retryWrites=true&w=majority
// server.js file
const express = require('express');
const dotenv = require('dotenv');
const colors = require('colors');
const morgan = require('colors');
const connectDB = require('./config/db')
dotenv.config({ path: "./config/config.env" })
connectDB();
const app = express();
const transactionsRouter = require('./routes/transactions')
app.use('/transactions', transactionsRouter)
const PORT = process.env.PORT || 5000;
app.listen(PORT, console.log(`server running in ${process.env.NODE_ENV} mode on port ${PORT}`.yellow.bold));

i am getting connection error on prod not localhost

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

MongoDB Error: connect ECONNREFUSED 35.156.235.216:27017

trying to connect mongoose to my express app and getting this error:
[nodemon] starting `node index.js`
Listening to the port 5000
connect ECONNREFUSED 35.156.235.216:27017
Im connecting the app directly to MongoDB Atlas, everything was working fine yesterday but this morning i got this Error. Here is the db connection file:
const mongoose = require("mongoose");
require("dotenv").config();
const connectDB = async () => {
try {
await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
});
console.log("connected to MongoDB..");
} catch (err) {
console.log(err.message);
}
};

MongoError: failed to connect to serve on first connect in mongoDB atlas

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"
}

Resources