MongoDB connection error in Digital Ocean droplet - mongodb

I am in the process of deploying my MERN app to a Digital Ocean droplet (Ubuntu 20.04 server).
I have cloned my GitHub repo to the droplet, installed the dependencies using npm install. Next, when I am starting the server using npm start, I get the following error:
The error essentially says that the first parameter to mongoose.connect() is undefined and must be a string. However, everything works fine in my local machine and when I console.log process.env.MONGO_URI, I get the connection string.
server/config/db.js
const mongoose = require("mongoose");
const colors = require("colors");
const dotenv = require("dotenv");
dotenv.config();
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
});
console.log(`MongoDB connected: ${conn.connection.host}`.cyan.bold);
} catch (error) {
console.error(`Error: ${error.message}`.red.bold.underline);
process.exit(1);
}
};
2;
module.exports = connectDB;
Why am I getting this error while starting the server in my Digital Ocean droplet?

dotenv doesn't load system variables.
Create .env file with
MONGO_URI=XXXXXXX
https://github.com/motdotla/dotenv#usage
Create a .env file in the root directory of your project. Add
environment-specific variables on new lines in the form of NAME=VALUE.
For example:
DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3

Related

Why is my data folder empty after I inserted data in mongodb local database?

Following the manual from npm mongodb webpage(https://www.npmjs.com/package/mongodb) I created in progect directory and then specified a database directory by typing mongod --dbpath=/data? then I launched this file:
app.js
const { MongoClient } = require('mongodb');
// Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
// Database Name
const dbName = 'myProject';
async function main() {
// Use connect method to connect to the server
await client.connect();
console.log('Connected successfully to server');
const db = client.db(dbName);
const collection = db.collection('documents');
const insertResult = await collection.insertMany([{ a: 1 }, { a: 2 }, { a: 3 }]);
console.log('Inserted documents =>', insertResult);
// the following code examples can be pasted here...
return 'done.';
}
main()
.then(console.log)
.catch(console.error)
.finally(() => client.close());
and I got success, but folder data is still completely empty. What is wrong?
Actually, when you call "dbpath=/data" even being in your directory with this folder created, this command in Windows means that your db will be stored in folder "C:/ProgramFiles/mongodb/data". To specify your progects folder, use full path

MongooseServerSelectionError: In Cpanel , Simple Routes are working But whenever try to Hit route of (MongoDb get/set) its Not Working. Mongodb error

Hy I have React NodeJs App, Trying to Deploy it On Cpanel Namecheap...
The site is Deploy Correctly. And Simple Routes are also Working but Routes that use to get/set data from DB is Note Working and stay in a loading state for long time...
I Also See my stderr.log file it says "MongooseServerSelectionError"...
But my MongoDB NetworkAccess is a enter image description herepublic already!!!!
Please Help..
here is my connection Code start.....
const mongoose = require("mongoose");
const connectDb = async () => {
mongoose.connect(
"mongodb://serverBoiler:myPassword#cluster0-shard-00-00.t30x6.mongodb.net:27017,cluster0-shard-00-01.t30x6.mongodb.net:27017,cluster0-shard-00-02.t30x6.mongodb.net:27017/RagdollCatServer?ssl=true&replicaSet=atlas-1r1rhb-shard-0&authSource=admin&retryWrites=true&w=majority",
{
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
}
)
.then((res) => console.log(`Db connected on ${res.connection.user}`));
};
module.exports = connectDb;
////////////////////////////////////////////////////////////////////////
You better try with localhost like this
it may help full I think.
var db="mongodb://localhost/loginapp"
mongoose.connect(db,{useNewUrlParser: true})
.then(()=>console.log('MongoDB successfully connected'))
.catch(err=>console.log(err));

How can I set TLS for Mongoose connection

I'm trying to migrate my mongo database from Compose to IBM Cloud Databases for Mongo and in their documnetations (https://www.compose.com/articles/exporting-databases-from-compose-for-mongodb-to-ibm-cloud/): "With a new Databases for MongoDB deployment, you'll be provided with a replica set of two endpoints to connect to your database. Databases for MongoDB also uses a TLS certificate, so you'll need to configure your MongoDB application driver to accept two hosts and a TLS certificate"
How can I set the TLS certificate provided by IBM Cloud in Mongoose connection ?
Nothing I've tried worked :(
I can see my database if I'm using the IBM cli but from my node.js application I cannot connect to it
var mongoose = require('mongoose');
mongoose.Promise = Promise;
var uri="mongodb://admin:passSftgdsdfvrrdfs#host1-1231243242.databases.appdomain.cloud:32605,host2-1231243242,host1-1231243242/testDatabaseName?authSource=admin&replicaSet=replset"
myDb.db = mongoose.createConnection(uri, {
tls: true,
tlsCAFile:`076baeec-1337-11e9-8c9b-ae5t6r3d1b17` (this is the name of the certificate and is placed in the root)
// tlsCAFile: require('fs').readFileSync('041baeec-1272-11e9-8c9b-ae2e3a9c1b17') // I have also tried something like this
absolute nothing is working even the database is there
Please help me
I'm also facing same problem
this works for me
mongoose.connect(‘mongodb+srv://username:password#host/db_name?authSource=admin&replicaSet=repliasetname&tls=true&tlsCAFile=/root/ca-certificate.crt’,{some config})
Try the following:
var key = fs.readFileSync('/home/node/mongodb/mongodb.pem');
var ca = [fs.readFileSync('/home/node/mongodb/ca.pem')];
var o = {
server: {
ssl: true,
sslValidate:true,
sslCA: ca,
sslKey: key,
sslCert:key
},
user: '****',
pass: '****'
};
m.connect('mongodb://dbAddr/dbName', o)```
I did it locally, you need to install the tunnel first
$ ssh -i "IF YOU HAVE PEM.pem" -L <27017:YOUR_AMAZON_HOST:27017> <server_user_name#server_ip_OR_server_url> -N
I managed to implement it as follows
const CERTIFICATE_PATH = 'rds-combined-ca-bundle.pem'
const certificateCA = CERTIFICATE_PATH && [fs.readFileSync(CERTIFICATE_PATH)];
const sslOptions = certificateCA
? ({
ssl: true,
tlsAllowInvalidHostnames: true,
sslCA: certificateCA,
user: MONGODB_USER,
pass: MONGODB_PASSWORD,
} as ConnectionOptions)
: {};
const options: ConnectionOptions = {
...sslOptions,
};
export const connectMongoDb = async (): Promise<void> => {
await mongoose.connect('mongodb://localhost:27017/test', options);
console.log('📊 Successfully connected to the database');
};
You need to set
MONGODB_USER
MONGODB_PASSWORD

Why does node server.js work, but node ./backend/server.js give me this error?

I currently have the following file directories:
and if i do node server.js while in the backend directory, the server runs. However, if I am in the root directory, and do node ./backend/server.js, the following error shows up:
Here is my code for the mongodb server on server.js:
const express = require('express');
const mongoose = require('mongoose');
const dotenv = require('dotenv')
dotenv.config();
const app = express();
app.use(cors({origin: true,credentials: true}));
app.use(express.json());
const PORT = process.env.port || 5000;
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true });
const connection = mongoose.connection
connection.once('open', () => {
console.log("MongoDB database connection established successfully");
})
I believe, it is because your .env file is not in the root.
Explanation:
When you run node server.js you application looks for .env file and load environment variables. But, when you navigate to root and run node ./backend/server.js it can't find .env file. So process.env.ATLAS_URI is undefined.

Connected to MLab, but won't connect to localhost

I had this working fine on both localhost and MLab, but then had to switch databases. After much trying I got the database up on MLab, but now it's not connecting to my localhost. Here is my server.js file:
const path = require("path");
const PORT = process.env.PORT || 3001;
const app = express();
const mongoose = require("mongoose");
const routes = require("./routes");
// Connect to the Mongo DB
mongoose.connect(process.env.MONGODB_URI || 'mongodb://XXUSERXX:XXPASSWORDXX#ds217388-a0.mlab.com:17388,ds217388-a1.mlab.com:17388/<dbname>?replicaSet=rs-ds217388', { useNewUrlParser: true });
mongoose.connection.on("open", function (ref) {
console.log("Connected to mongo server.");
});
mongoose.connection.on('error', function (err) { console.log(err) });
// Define middleware here
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// Serve up static assets (usually on heroku)
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"));
}
// Add routes, both API and view
app.use(routes);
// Define API routes here
// Send every other request to the React app
// Define any API routes before this runs
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "./client/build/index.html"));
});
app.listen(PORT, () => {
console.log(`🌎 ==> API server now on port ${PORT}!`);
});
The only line of code I changed was this one below, this is what it was previously:
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/wineDB', { useNewUrlParser: true });
I have this app connected in Heroku and had MONGODB_URI defined in the Config Vars, but it wasn't working with the second database until I manually put the connection string in my server.js file. It worked fine with the first one, I don't understand why!
How do I get it to connect to find localhost when it's not running off of MLAB so I can test? Thanks for the help.
It looks like the confusion is from a few different combinations of whether the environment variable being defined or not, as well as whether or not your app is using the variable, instead of falling back to what is defined.
The MONGODB_URI environment variable should contain the connection string for your mLab database and be defined in your Heroku environment both locally and when deployed. I'm assuming that the variable process.env.LOCAL will only be present on your local environment, in situations where your app should be connecting to the local database.
In these cases, something like the following should work:
if(process.env.LOCAL || process.env.MONGODB_URI) {
mongoose.connect(process.env.LOCAL || process.env.MONGODB_URI, { useNewUrlParser: true });
...
} else {
console.log("MongoDB connection string not defined!");
}
We place process.env.LOCAL first, followed the by ||, to say that it gets preference when connecting. Mongoose should then connect to whatever is defined in process.env.LOCAL if present (i.e. your local MongoDB database), falling back to process.env.MONGODB_URI (i.e. mLab) otherwise.
Lastly, it's wrapped in a simple if-else to print out an error message if both values are not defined.