First of all, I humbly request you to read the full texts, I had to write many paragraphs to explain the situation clearly.
I have a nodejs
/express
application. And I am using mongoose
to handle operations of MongoDB. I have stored MongoDB connection string in .env
file and the file which connects to database looks like this,
const mongoose = require("mongoose");
require("dotenv/config");
mongoose.connect(process.env.DB_CON_STRING, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false,
});
const connectionStatus = mongoose.connection;
connectionStatus.on("open", (_) => console.log("Connected to DB"));
connectionStatus.once("error", (err) => console.log(err));
I have a login route like every other application and everything work perfectly fine in local. As it was working perfectly fine in local, I decided to test in an environment similar to production.
In order to make it production ready, I manually created the database and created user and using that user I have inserted one document in a collection. This document holds the data I will need to login to the application. And I have started the application on a ubuntu server inside of DigitalOcean droplet.
Normally when I send login request to the app running on my local machine, it works fine. But when I sent login request to the remote endpoint, I got error. And FYI, it is nothing to do with CORS. I have set it to allow from where I am making the request. After logging the error, I got something like this,
MongoError: not authorized on test to execute command
This is just frustrating. I don't understand why the same thing working in local but not in remote. I can 100% assure you I have setup database on remote machine, created user and my database connection string is also fine in remote. And my database is not 'test'. So, why it is doing on test?
Earlier I told that I have a database and a user for that database. I logged in that database with the user in my ubuntu server and inserted data. The database connection string exactly says to connect to the right database with correct credentials.
Someone please help me by explaining what's going on. This is so much frustrating.
This has to be error in the connection string. A proper and working connection string would be like this,
mongodb://user
:password
@host
:port
/databaseName
?authSource=databaseName
So, the user
here is of course your database user, password
is password. host
is your host, most commonly 'localhost' and port
is most commonly '27017'. And after the slash, there should be database name as well as in the auth source. Example connection string,
mongodb://ziondork:123456@localhost:27017/myDB?authSource=myDB
There must be something wrong in your connection string, most probably on the last part where you specify the database name and authentication source.