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
You can connect to MongoDB with the mongoose. connect() method. mongoose. connect('mongodb://localhost:27017/myapp');
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.
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.
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With