How can connect to mongo db authentication by node.js

I want to join mongodb by node.js
localhost with authenticated user
I made this steps as follow
1- run mongo from bin

2- use ais_mlm db

3-createUser admin with password admin

4- edit config file to authorization enable

5- restart mongodb server from task manager
6- go to node.js project folder and run nodemon
show error cannot connect to mongodb
here is string url for this

DATA = “mongodb://admin:admin@localhost:27017/ais_mlm?authSource=admin”

here is db.js file

const mongoose = require("mongoose");
//const mongoDB = "mongodb://admin:admin@localhost:27017/ais_mlm?authSource=admin";
const chalk = require('chalk');
const path = require('path');
const connected = chalk.bold.cyan;
const error = chalk.bold.yellow;
const disconnected = chalk.bold.red;
const termination = chalk.bold.magenta;
require('dotenv').config({ path: path.resolve(__dirname, '../.env') });
console.log('here...', path.resolve(__dirname, '../.env'),process.env.DATA);

 mongoose.connect(process.env.DATA,{ useNewUrlParser: true, useUnifiedTopology: true } ,async(err)=>{
    if(err) throw err;
    console.log("conncted to db")
  }
 );

mongoose.connection.on('connected', function(){
    console.log(connected("Mongoose default connection is open to ", process.env.DATA));
});

mongoose.connection.on('error', function(err){
    console.log(error("Mongoose default connection has occured "+err+" error"));
});

mongoose.connection.on('disconnected', function(){
    console.log(disconnected("Mongoose default connection is disconnected"));
});

process.on('SIGINT', function(){
    mongoose.connection.close(function(){
        console.log(termination("Mongoose default connection is disconnected due to application termination"));
        process.exit(0)
    });
});
//module.exports.mongoDB = mongoose;

please show me what is wrong and how can connect this
thanks.
I wasted so many hour in this error
I need help.

lol ,noone answer, what kind of community.

1 Like

Welcome to the MongoDB Community Forums @kyaw_swar_lin !

I suspect the issue is that according to your steps you have created an admin user in the ais_mlm database:

… but are using the admin database as your authentication source via the authSource parameter in your connection string:

DATA = “mongodb://admin:admin@localhost:27017/ais_mlm?authSource=admin”

Creating the user in the admin database or using ais_mlm as the authSource value should resolve this problem.

If you are still having trouble, it would be helpful to provide more information:

  • Your MongoDB Node.js driver version
  • Your Mongoose version
  • The specific error message returned by the driver
  • Whether you are able to connect to your deployment with authentication disabled

Regards,
Stennie

1 Like

Sorry bro, I would have helped you but am new to the MongoDB technology

I’m facing the same kind of error. My condition is as follows:

I create a user in the user database with
name: “rootadmin”
pwd: “root@123”
roles roles: [ { role: ‘userAdminAnyDatabase’, db: ‘admin’ } ],

I have already created the TASK-MANAGER database.

And I’m trying to connect from express js with the following setup:

option 1:

mongoose.connect("mongodb://rootadmin:'root@123'@localhost:27017/TASK-MANAGER?authSource=admin", {
        useNewUrlParser: true,
        useUnifiedTopology: true
    })

option 2:

mongoose.connect("mongodb://rootadmin:root@123@localhost:27017/TASK-MANAGER?authSource=admin", {
        useNewUrlParser: true,
        useUnifiedTopology: true
    })

I tried both options to connect to DB but it threw an error:

TypeError [ERR_INVALID_URL]: Invalid URL
at new NodeError (node:internal/errors:372:5)
at URL.onParseError (node:internal/url:553:9)
at new URL (node:internal/url:629:5)
at isAtlas (G:\My Projects\express_js\task_manager\node_modules\mongoose\lib\helpers\topology\isAtlas.js:17:17)
at MongooseServerSelectionError.assimilateError (G:\My Projects\express_js\task_manager\node_modules\mongoose\lib\error\serverSelection.js:35:35)
at G:\My Projects\express_js\task_manager\node_modules\mongoose\lib\connection.js:813:36
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
input: ‘123:27017’,
code: ‘ERR_INVALID_URL’
}

Please help me to fixed it
Thank You.

Your password root@123 completely screw up the URI parser because the @ is used as a separator between the credentials and the host part. So it tries with the password root and the host 123@localhost.

Do not put @ in your passwords.

2 Likes

You are right. thank you.