Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to authenticate mongoose connection mongodb in node.js

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

like image 525
sarfarazsajjad Avatar asked Nov 02 '14 00:11

sarfarazsajjad


People also ask

Which method is used to connect MongoDB instance using Mongoose?

You can connect to MongoDB with the mongoose. connect() method. mongoose. connect('mongodb://localhost:27017/myapp');

How do I know if MongoDB is connected node?

isConnected runs getDbObject . getDbObject connects to mongoDB and returns an object: connected (true/false), db (dbObject or error). Then, isConnected resolve/reject by connected property.


2 Answers

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.

like image 160
Joe Coyle Avatar answered Sep 18 '22 09:09

Joe Coyle


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();
});
like image 36
scuencag Avatar answered Sep 17 '22 09:09

scuencag