Get connection instance

0

I would like to get the connection from the dbConnection.js file, but run the query on another file (DAO).

I'm doing a NodeJS course and what I've learned is getting this connection and using a 'gerialized' method to run the queries. (in dbConnection.js)

However, I would like to execute queries within DAO for what I am dealing with.

The code below represents my dbConnection.js file

    var mongo = require("mongodb").MongoClient;
    var assert = require("assert");
    const url = "mongodb://localhost:27017";
    const dbName = "got";

    // Meu método de obter conexão com banco de dados
    var connMongoDB = function () {

         mongo.connect(url, { useNewUrlParser: true }, function connectCallback(err, client) {

         // Teste simples para comparar um resultado esperado com um resultado real 
         assert.equal(null, err);

         // Cria uma nova instância db  
         const db = client.db(dbName);


         // Fecha conexão 
         client.close();

      });

     }

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

The code below represents my file UsuariosDAO.js

    function UsuariosDAO(connection) {
       this._connection = connection;
    }

    UsuariosDAO.prototype.inserirUsuario = function (dados, res) {

    var collection = this._connection.collection("usuarios");

            switch (dados.operacao) {
             case "inserir":
              collection.insertOne(dados.usuario, dados.callback);
             break;
            default:
             break;
            }

    };

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

The code below represents my cadastro.js (controller) file

/* Criando a conexão com banco */
var connection = application.config.dbConnection;

/* Instanciando a 'classe' do usuario e passando a conexão para o construtor */
var UsuariosDAO = new application.app.models.UsuariosDAO(connection);

/* Chamando o método para inserção do usuario */
UsuariosDAO.inserirUsuario(dadosForm, res);

Error:

TypeError: this._connection.collection is not a function
    
asked by anonymous 28.12.2018 / 12:51

2 answers

1

Hello,

For what it seems, it is not being exported to the instance of the connection, I was looking at your connection file and made some changes to try to solve it:

var mongo = require("mongodb").MongoClient;
var assert = require("assert");
const url = "mongodb://localhost:27017";
const dbName = "got";

// Meu método de obter conexão com banco de dados
var connMongoDB = function () {

     mongo.connect(url, { useNewUrlParser: true }, function connectCallback(err, client) {

     // Teste simples para comparar um resultado esperado com um resultado real 
     assert.equal(null, err);

     // Cria uma nova instância db  
     db = client.db(dbName);
     return db;

  });

 }

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

I hope it helps

    
28.12.2018 / 21:20
0

I know what course you are doing, it is very good, but it is a bit outdated, but I can help you by informing you that at the end of the course, in the "course complement" section you will see a PDF file with the explanations that correct and add new methods to solve the problem. But I will leave the explanations below for you to analyze. I hope it helps:

   var mongo = require("mongodb").MongoClient;
   var assert = require("assert");
   const url = "mongodb://localhost:27017";
   const dbName = "got";
   var connMongoDB = function (dados) {
     mongo.connect(url, function (err, client) {
      assert.equal(null, err);
      console.log("Connected successfully to server");
      const db = client.db(dbName);
      query(db, dados);
      client.close();
     });
   };

   function query(db, dados) {
    var collection = db.collection(dados.collection);
    switch (dados.operacao) {
     case "inserir":
      collection.insertOne(dados.usuario, dados.callback);
      break;
     default:
      break;
  }
 }
 module.exports = function() {
  return connMongoDB;
 };

Let's go to the explanations, at the beginning of the code there is the import of MongoClient that has to be used in the new version, and just below comes the assert import, which was used to check for errors in connecting to the database. Following are the credentials of the bank, first the url for connection and then the name of the database that we want to connect. We get to the connection function, the connMongoDB variable remains the same, which changed was its scope and parameters received, now we receive in connection an object as a parameter, with the data for the connection and manipulation of the data, but not worry, it will be explained later on the parameters, within the function we use the variable imported at the beginning to call the connect method passing some data to the connection, and it is in the callback of this function that we execute the operations in the database, inside the callback function the first thing we check is if there were no errors in the connection, if it did not, we arrived at the declaration of variable db that database that we want to execute the operations, then we call the function query that is who will carry out the operations, let's talk about it below, and finally to not generating multiple connections, we use the client.close () command to finalize the connection.

The query function was created to avoid code repetition because otherwise we would have to create the entire connection configuration for each operation that was with the query function we can only insert a case on the switch for each operation and within the case indicate what exactly we want to do, in the code example above there is the insert case and inside it we have the command collection.insertOne (data.user, data.callback), this command will insert a document into the collection users and then render a page, I will explain in the sequence what are the parameters passed to this function.
The file UsuariosDAO.js that previously called the connection within each function indicating the operation to be done and the callback now only creates a data object and the passes to the connection, the new code looks like this:

    function UsuariosDAO(connection) {
     this._connection = connection;
    }
    UsuariosDAO.prototype.inserirUsuario = function(usuario, res) {
     var dados = {
      operacao: "inserir",
      usuario: usuario,
      collection: "usuarios",
      callback: function(err, result) {
       res.send("olá Marilene");
      }
     };
     this._connection(dados);
   };
   module.exports = function() {
    return UsuariosDAO;
   };

As you can see inside the function insertUsuario we create a data object containing some settings to perform the operation in the database, these indices within the object must be standard for any operation to be performed, they are them:

 operation = Must receive a string that matches the query function case  user = It is a variable index, depending on the case you can pass others data, for example, pass the news index to add news, just adjust in case which one to use

collection = Must receive a string indicating which collection will be manipulated in the bank

callback = Must receive a function to be executed in response to execution of the operation in the database

And finally we call the connection passing this object. Using this new model, which has already been tested, operations in the database normally occur.

    
28.12.2018 / 20:23