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 =;
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(){
        console.log(termination("Mongoose default connection is disconnected due to application termination"));
//module.exports.mongoDB = mongoose;

please show me what is wrong and how can connect this
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


1 Like

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