I have a web application that connects to MongoDB. Everything works fine before I create the admin user in mongodb:
db.createUser(
{
user: "admin",
pwd: "password",
roles: [ { role: "root", db: "admin" } ]
}
);
The URL the API wrote in the .env
file
- before:
mongodb://localhost:27017/shrimp
- after:
mongodb://admin:password@localhost:27017/shrimp
I tied to add a different user, it still doesn't work
- url: mongodb://user:newpassword@localhost:27017/shrimp
The weird thing is, when I use mongodb://admin:password@localhost:27017/shrimp
in
mongoDB Compass, it can connect, but when I use mongodb://user:newpassword@localhost:27017/shrimp
it says "Authentication failed."
EDIT
The tools I use: mongoose, Windows 10, NextJS.
The mongodb://user:newpassword@localhost:27017/shrimp
can connect to mongoDB Compass now: mongodb://user2:1234@localhost:27017/shrimp?authSource=shrimp
and I try using same code to the dbconnection.js:
const URL ="mongodb://user2:1234@localhost:27017/shrimp?authSource=shrimp"
ANSWER
Short answer: add ?authSource=shrimp
Long answer:
- after creating the admin user, check the
mongod.cfg
file. How to set authorization in mongodb config file? - login to mongo to check whether it's a success
mongo --host localhost --port 27017 -u admin -p --authenticationDatabase admin
- testing the mongo URL format whether it can login in MongoDB Compass
mongodb://admin:password@localhost:27017/admin?authSource=admin
if can login MongoDB Compass the link should work in JS file
Resulting code
const mongoose = require("mongoose")
const URL ="mongodb://admin:password@localhost:27017/admin?authSource=admin"
const connection = {};
async function dbConnect() {
if (connection.isConnected) return;
const db = await mongoose.connect(URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
connection.isConnected = db.connections[0].readyState;
console.log(connection.isConnected)
}
module.exports = dbConnect;