14

I have created mongodb user with command

use admin
db.createUser(
    {
      user: "superuser",
      pwd: "12345678",
      roles: [ "root" ]
    }
)

then in my app I am trying to connect mongoose like this

var options = {
user: "superuser",
pass: "12345678"
};


var mongooseConnectionString = 'mongodb://localhost/twitter-mongo';

mongoose.connect(mongooseConnectionString,options);
mongoose.model('User', UserSchema);

var User = mongoose.model('User');

I am getting this error when inserting data through mongoose

MongoError: not authorized for insert on twitter-mongo.users

please tell me what is wrong in my code

sarfarazsajjad
  • 1,208
  • 2
  • 17
  • 30

7 Answers7

37

You must declare the authSource parameter in your connection string in order to specify the name of the database that contains your user's credentials:

var options = {
  user: "superuser",
  pass: "12345678"
};

var mongooseConnectionString = 'mongodb://localhost/twitter-mongo?authSource=admin';

Note: for users of Mongoose 4.x, you may want to also include useMongoClient: true in your options object. This silences the Please authenticate using MongoClient.connect with auth credentials and open() is deprecated error messages.

Joe Coyle
  • 601
  • 6
  • 15
10

This is working fine:

var options = { server: { socketOptions: { keepAlive: 1 } } };
var connectionString = 'mongodb://admin:admin1234@localhost:27017/myDB';

 mongoose.connect(connectionString, options);

//Add those events to get more info about mongoose connection:

// Connected handler
mongoose.connection.on('connected', function (err) {
  console.log("Connected to DB using chain: " + connectionString);
});

// Error handler
mongoose.connection.on('error', function (err) {
  console.log(err);
});

// Reconnect when closed
mongoose.connection.on('disconnected', function () {
   self.connectToDatabase();
});
scuencag
  • 664
  • 4
  • 11
4

try this

const mongooseConnectionString = 'mongodb://superuser:12345678@ localhost/twitter-mongo?authSource=admin'
sajan
  • 1,355
  • 1
  • 14
  • 19
2

I did run a mongo service using docker and then connected my mongoose to it with this code

const _database = 'mongodb://user:pass@localhost:port/MyDB?authSource=admin';
mongoose.connect(_database, {
    useNewUrlParser: true
})
.then(() => console.log('Connected to MongoDB ...'))
.catch(err => console.error('Could not connect to MongoDB:‌', err));

this is equal to

mongo --username user --password pass --authenticationDatabase admin --port 27017

on connection and then use MyDB database for doing operations like find, aggregate, insert and etc on it.

if you have no user (MongoDB default user) for your database then you can change Database like bellow:

const _database = 'mongodb://localhost:port/MyDB';

27017 is default MongoDB port if your MongoDB port hasn't changed either then you can do the same for port too. like bellow:

const _database = 'mongodb://localhost/MyDB';

this is the same as bellow:

mongo

above code is because there is no user and no port then for not been a user there is no need for authentication database either.

adnan ahmady
  • 770
  • 1
  • 7
  • 12
1
mongoose.createConnection('mongodb://username:password@35.238.xxx.xxx:27017/dashboards?authSource=admin', {
   useNewUrlParser: true
}, (e) => {

    if (e) throw console.error('Error connecting to mongo database master');
    console.log('Connected to mongo database master.');

});
Mario Callejas
  • 101
  • 1
  • 2
  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Piotr Labunski Feb 18 '20 at 22:08
0

You need to create an User in database which you are operating on, not the admin DB.

Use this command,

use twitter-mongo;
db.createUser({
  user: "superuser",
  pwd: "12345678",
  roles: [ "root" ]
});

Instead of this,

use twitter-mongo
db.createUser({
  user: "superuser",
  pwd: "12345678",
  roles: [ "root" ]
});
Alagarasan M
  • 907
  • 8
  • 16
0

Correct way to create the connection string is var connection = mongoose.createConnection("mongodb://username:pwd@hostip:port/dbname?authSource=admin", options);

Please use authSource=admin to authenticate in connection string.

Ari
  • 341
  • 2
  • 14