Get instance of connection

Asked

Viewed 288 times

0

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

I am taking a Nodejs course and what I have learned is to get this connection and use a 'managed' method to run the queries. (in dbConnection.js)

However, I would like to run the queries within the 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 Usuariosdao.js file

    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.js register file (controller)

/* 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

2 answers

1

Hello,

From what it seems, is that the instance of the Connection is not being exported, I have been looking at your connection file and made some changes, to try to resolve:

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;
 };

hope it helps

  • Hey buddy, I haven’t tried it yet, but it probably won’t work. Note that Return does not belong to the function assigned to connMongoDB, but rather to the function of Mongo.connect. In practice it would pass this db to the function continues in the variable connMongoDB and later export this connection. But thank you!

0

I even know what course Oce is doing, it is very good but it is a little outdated, but I can help you by informing you that at the end of the course, in the section "complement of the course" You will see a PDF containing the explanations that correct and add new ways to solve the problem. But I’ll leave the explanations below for you to review. 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 explain, 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 verify errors in connection with the database.
In the sequence we have the variables of credentials of the bank, first the url to connection and then the name of the database we want to connect.
We arrived at the connection function, the connMongoDB variable remains the same, which changed was its scope and received parameters, now we received in connection an object as a parameter, with data for connection and data manipulation, but not if worry, will be explained further on the parameters, within the function we use the Imported variable at the beginning to call connect method passing some data to the connection, and it is in the callback of that function that we perform the operations in the database, within the callback function the first thing we check is if there were no errors in the connection, if there was no we arrived at the declaration of the variable db that keeps the reference of the database we want to perform operations, then we call the function which is who will carry out the operations, let’s talk about it right below, and finally to not being generated multiple connections we use the client.close() command to finish the connection.

The query function was created to avoid code repetition, since the otherwise we would have to create the entire connection configuration for each operation that was performed, with the query function we can just insert a case into the switch for each operation and inside 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 in the users' Collection and in then render a page, I will explain in sequence what are the parameters passed to that function.
The Usuariosdao.js file that used to call 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 was as follows:

    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 insert functionUsuario 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, are they:

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

Collection = Should receive a string indicating which Collection will be bank-rigged

callback = Must receive a function to be executed as a response from execution of the transaction in the database

And finally we call the connection by passing this object.

Using this new model, which has already been tested, operations in the database occur normally.

  • Friend, I already have access to this document available in the course, but I would like to implement it in another way. See that I have my query method inside the file that I get the database connection, and in practice I would not like to do this, I wanted to treat each query in its DAO file. For this I need to export the connection of the file that obtains connection.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.