MongoDB, a cross-platform document-oriented database. Classified as a NoSQL database, MongoDB eschews the traditional table-based relational database structure in favor of JSON-like documents with dynamic schemas (MongoDB calls the format BSON), making the integration of data in certain types of applications easier and faster.
Here I am going to explain how to apply user-name and password(authenticate) to mongoDB’s database.
command – mongo
output-
MongoDB shell version: 3.0.4
connecting to: test
command – show dbs;
output-
admin 0.078GB
local 0.078GB
auth_db 0.078GB
command – use auth_db;
output-
switched to auth_db
Here, we have selected auth_db Database for apply authentication.
db.createUser({user:”YOUR_USERNAME”, pwd:”YOUR_PWD”,roles:[“readWrite”,”dbAdmin”]})
We have created User of database ‘auth_db’. You can set your user-name and password to above query.
Make sure authentication is true. You can set authentication = true in MongoDB.conf file.
var mongoose = require('mongoose');
var uri = 'mongodb://localhost:27017/auth_db';
var options = {
user: 'YOUR_USERNAME',
pass: 'YOUR_PWD'
}
mongoose.connect(uri, options, function(err, result){
console.log('err -->' + JSON.stringify(err));
});
Without user-name and password, would not able to perform an operation with the database. If you don’t want to use authentication to database just make auth=true is commented in MongoDB.conf file or start mongo without -auth i.e mongo . Please do not forget restart MongoDB.
You can drop a comment for any questions or feedback. We Will get back to you soon.