0

I'm trying to configure the connetion in my dbConnection.js
to connect my MongoDb hosted in Mlab to my NodeJs app hosted in Heroku.

I believe the problem is permisson.

My question: How can I configure the "connectionString" using ONLY the default MongoDb Driver (without Mongoose and similars for exemple plz. I want to make and learn with basic and default method)

My apllication structure: enter image description here


My apllication has a App.Js that calls server.js

/* importar as configurações do servidor */
var app = require('./config/server');


var port = (process.env.PORT || 8080);

/* parametrizar a porta de escuta */
app.listen(port, function(){
    console.log('');
    console.log('|*****************************************************|');
    console.log('|----------- Servidor online na porta: ' + port + ' ----------|');
    console.log('|*****************************************************|');
    console.log('');
})

My server.js uses MongoDb including dbConnection.js.

server.js

...some code

mongodb  = require('mongodb'), //  <--- var para o banco de dados
objectId = require('mongodb').ObjectId;

//var url = PROD_MONGODB //'mongodb://localhost:27017/my_database_name';      
var url = process.env.MONGOLAB_URI;

... some code

My dbConnection.js var connMongoDB is:

 /* Importar o MongoDB */
var mongo = require('mongodb');


/*var connMongoDB =  function(){
    console.log('========== Entrou na function de connection!  =============');
    var db = new mongo.Db(
            'OPDC',             // PARAM 1 = nome do banco
            new mongo.Server(   // PARAM 2 = objetos basicos de conexao
                'localhost', // string  contendo o endereco  do servidor
                27017,       // porta       
                {}           // opc de config do servidor
            ),
            {}                  //  PARAM 3 = configs opcionais
        );

    return db;
}*/


var connMongoDB =  function(){
    console.log('========== Entrou na function de connection!  =============');
    var db = new mongo.Db(
            'heroku_f6bst99r',       // PARAM 1 = database name
            new mongo.Server(        // PARAM 2 = basic objects for connection
                'ds129776.mlab.com', // string  with the server address
                29776,       // port        
                {}           // server config options?
            ),
            {}                  //  PARAM 3 = opcionals configs 
        );

    return db;
}

module.exports = function(){
    return connMongoDB;
}

Some observations:

  • Localhost (app and database) all works
  • Published Node still works without database connection (a simple return message for exemple
  • I can Connect and use my hosted Mlab MongoDb still

The error is that below: Address: https://opdcapi.herokuapp.com/ Error:

{"name":"MongoError","message":"not authorized on heroku_f6bst99r to execute command { find: \"brand\", filter: {} }","ok":0,"errmsg":"not authorized on heroku_f6bst99r to execute command { find: \"brand\", filter: {} }","code":13,"codeName":"Unauthorized"}

GITHUB PROJECT: https://github.com/frotaadriano/opdc_nodeAPI

enter image description here

4
  • Use mongoClient instead, its better Commented Dec 11, 2017 at 1:27
  • I already use mongoClient in DAO IndexDAO.prototype.getBrands= function(res){ //res.send({msg:'the API is online!!!!!!!!! '}); this._connection.open( function(err, mongoclient){ mongoclient.collection("brand", function(err, collection){ collection.find().toArray(function(err, result){ console.log(result); if(err){ //res.status(404).json(err); res.json(err); }else{ //res.status(200).json(result); res.json(result); } mongoclient.close(); // fechar a conexao }); }); }); } Commented Dec 11, 2017 at 1:33
  • Then just Mongoclient.connect("mongod://<mlab username>:<mlab pass>@<address>.mlab.com:<PORT>/<database name>") eg mongodb://<adminuser>:<password>@ds012345-a0.mlab.com:56789/mydb Commented Dec 11, 2017 at 1:37
  • where in my code can I put this?? Commented Dec 11, 2017 at 1:43

1 Answer 1

0

In dbConnection.js:

const MongoClient = require('mongod').MongoClient;
const dbUrl = "mongod://<mlab username>:<mlab pass>@<address>.mlab.com:<PORT>/<database name>";

MongoClient.connect(dbUrl,function(err,db){
           //code
});
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry but I didnt understand all changes I need to Do. I have The dbConnection.js and I pass application to index in route, after Index in Controller and at least IndexDAO. Do I need to replace all dbConnection.js to your suggestion code? And Where Can I execute my CRUDs, inside dbConnection instead my MVC structure?
Yes you can reaplce your dbconnection but have to export the db object from dbConnection.js to operate CRUD operations in other files. How to export i can answer but there are already many answers present like: stackoverflow.com/questions/17647779/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.