I am trying to connect to mongodb and querying data from it. Here is what I am doing:
In node js my db connection file is looks like this:
//Using mongodb drivers has to be installed using npm
var MongoClient = require('mongodb').MongoClient;
var dburl = 'mongodb://localhost:27017/meanhotel';
var _connection = null;
var open = function() {
MongoClient.connect(dburl, function(err, db) {
if (err) {
console.log("DB connection failed",err);
return;
}else{
_connection = db;
console.log("DB connection open");
}
});
};
var get = function() {
return _connection;
};
module.exports = {
open : open,
get : get
};
And the node js code which I am using to query data from the database is like this:
var dbconn = require('../data/dbconnection.js');
var hotelData = require('../data/hotel-data.json');
module.exports.hotelsGetAll = function(req, res) {
//
var db = dbconn.get();
var collection = db.collection('hotels');
var docs=collection.find();
collection
.find()
.toArray(function(err,docs){
console.log("Found hotels",err);
res
.status(200)
.json(docs);
});
If I visit the URL
Nothing is coming out.
Also in terminal I am getting this output.
Found hotels { [MongoError: not authorized on meanhotel to execute command { find: "hotels", filter: {} }]
name: 'MongoError',
message: 'not authorized on meanhotel to execute command { find: "hotels", filter: {} }',
ok: 0,
errmsg: 'not authorized on meanhotel to execute command { find: "hotels", filter: {} }',
code: 13,
codeName: 'Unauthorized' }
I am using this for launch the mongo shell:
mongo localhost:27017/admin -u user -p pass
Also if I want to dump data to the database I am using this.
sudo mongodump --db meantest -u user -p pass --authenticationDatabase
admin --gzip
What could be going wrong?
Best Answer
The right URL format when MongoDB authentication is enabled is:
mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
For your case: mongodb://user:pass@localhost:27017/meanhotel?authSource=admin
Reference: MongoClient or how to connect in a new and better way