Command insert requires authentication when connecting to remote server of database | code: 13, codeName: Unauthorized

I’m able to connect to the remote server

const express =require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const Promise = require('bluebird');
Promise.promisifyAll(mongoose);

const app = express();

mongoose.connect("mongodb://<Username>:<Password>@<RemoteHost>:<Port>/user")
  .then(function(){
        console.log("Connected to database");
       })
  .catch(function(err){
       console.log("Connection failed", err);
  });

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static("public"));


// Below is the schema and the database model

const userSchema = new mongoose.Schema({

    role_id: {type:Number},
    name:{ firstName:{type:String},
           middleName: {type:String},
           lastName: {type:String}
        },
    contact:{
        mobileNo:{type:Number},
        mail_id:{ 
             username:{type:String},
             password:{type:String}
              }
        },
    address: {type:String},
    pincode: {type:Number},
    city: {type:String},
    state: {type:String}
    
});

const User = mongoose.model("users",userSchema);

// Below is the get,post method

app.get("/getusers",function(req,res){
  User.find(function(err,foundUsers){   
    if(err){
      res.send(err);
    } else {
      res.send(foundUsers);
    }
  });
});

app.post("/getusers",function(req,res){
  try {
    const newUser = new User({
      role_id: req.body.role_id ,
      name:{
        firstName:  req.body.name.firstName,
        middleName: req.body.name.middleName,
        lastName: req.body.name.lastName
      },
      contact:{
        mobileNo: req.body.contact.mobileNo,
        mail_id:{
          username: req.body.contact.mail_id.username,
          password: req.body.contact.mail_id.password
        }
      },
      address: req.body.address,
      pincode: req.body.pincode,
      city: req.body.city,
      state: req.body.state
    });
    newUser.save();
    
  } catch (error) {
    console.log(error);
  }
})

Now after calling API from software or postman I’m getting below error

/Documents/mProject/node_modules/mongodb/lib/cmap/connection.js:207
                    callback(new error_1.MongoServerError(document));
                             ^

MongoServerError: command insert requires authentication
    at Connection.onMessage (/Documents/mProject/node_modules/mongodb/lib/cmap/connection.js:207:30)
    at MessageStream.<anonymous> (/Documents/mProject/node_modules/mongodb/lib/cmap/connection.js:60:60)
    at MessageStream.emit (node:events:513:28)
    at processIncomingData (/Documents/mProject/node_modules/mongodb/lib/cmap/message_stream.js:132:20)
    at MessageStream._write (/Documents/mProject/node_modules/mongodb/lib/cmap/message_stream.js:33:9)
    at writeOrBuffer (node:internal/streams/writable:391:12)
    at _write (node:internal/streams/writable:332:10)
    at MessageStream.Writable.write (node:internal/streams/writable:336:10)
    at Socket.ondata (node:internal/streams/readable:754:22)
    at Socket.emit (node:events:513:28)
    at addChunk (node:internal/streams/readable:315:12)
    at readableAddChunk (node:internal/streams/readable:289:9)
    at Socket.Readable.push (node:internal/streams/readable:228:10)
    at TCP.onStreamRead (node:internal/stream_base_commons:190:23) {
  ok: 0,
  code: 13,
  codeName: 'Unauthorized',
  [Symbol(errorLabels)]: Set(0) {}
}

I’ve tried below combinations for mongoDB connections

  1. mongoose.connect(“mongodb://${Username}:${Password}@${RemoteHost}:${Port}/user”)
  2. mongoose.connect(“mongodb://${RemoteHost}:${Port}/user”)
  3. mongoose.connect(“mongodb://${RemoteHost}/user”)
  4. mongoose.connect(“mongodb://${Username}:${Password}@${RemoteHost}/user”)
  5. mongoose.connect(“mongodb+srv://${Username}:${Password}@${RemoteHost}:${Port}/user”)
  6. mongoose.connect(“mongodb+srv://${RemoteHost}:${Port}/user”)
  7. mongoose.connect(“mongodb+srv://${RemoteHost}/user”)
  8. mongoose.connect(“mongodb+srv://${Username}:${Password}@${RemoteHost}/user”)

So please respond if you found any answers

1 Like

Hi @R_V - Welcome to the community

 codeName: 'Unauthorized',

I’ve tried below combinations for mongoDB connections
mongoose.connect(“mongodb://${Username}:${Password}@${RemoteHost}:${Port}/user”)
mongoose.connect(“mongodb://${RemoteHost}:${Port}/user”)
mongoose.connect(“mongodb://${RemoteHost}/user”)
mongoose.connect(“mongodb://${Username}:${Password}@${RemoteHost}/user”)
mongoose.connect(“mongodb+srv://${Username}:${Password}@${RemoteHost}:${Port}/user”)
mongoose.connect(“mongodb+srv://${RemoteHost}:${Port}/user”)
mongoose.connect(“mongodb+srv://${RemoteHost}/user”)
mongoose.connect(“mongodb+srv://${Username}:${Password}@${RemoteHost}/user”)

I do not believe this is due to the above combinations of connection strings used. The unauthorized error generally indicates that the associated database user does not have sufficient privileges to perform a particular action. You may find the following Built-In Roles documentation useful as a reference point.

Regards,
Jason

2 Likes

Thank you for the solution. It did helped.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.