Node and Mongodb connection problems

Asked

Viewed 301 times

0

A few days ago I’m having a problem with a code that I’m having trouble solving. What I’m trying to do at the moment is to register users in mongodb through Node. I am using the view ejs mechanism, but so far I have checked everything and it is correct, the only problem is in the implementation of the function that opens the connection to the Mongodb bank. I am using the standard MVC, follows below the codes.

dbConnection.js file that connects to the database (so far everything seems to be ok):

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

var connMongoDB = function(){
    console.log('Entrou na função de conexão');
    var db = new mongo.Db(
        'crud',
        new mongo.Server('localhost',
            27017,
            {}
        ),
        {}
    );

    return db;
};

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

Route register.js (seems to be ok tbm):

module.exports = function(application, res, res){
application.get('/cadastro', function(req, res){
    application.app.controllers.cadastro.cadastro(application, req, res);
});

application.post('/cadastrar', function(req, res){
    application.app.controllers.cadastro.cadastrar(application, req, res);
});
};

Register Controller(Until then I still did the test by passing a console.log of the data variableForm and was returning the data entered in the form normally) :

module.exports.cadastro = function(application, req, res){
res.render('cadastro', {validacao: {}, dadosForm: {}});
};

module.exports.cadastrar = function(application, req, res){

var dadosForm = req.body;

req.assert('nome', 'Nome não pode ser vazio').notEmpty();
req.assert('usuario', 'Usuário não pode ser vazio').notEmpty();
req.assert('senha', 'Senha não pode ser vazio').notEmpty();

var erros = req.validationErrors();

if(erros){
    res.render('cadastro', {validacao: erros, dadosForm: dadosForm});
    return;
};

var connection = application.config.dbConnection; // retorna a variável connMongoDb
var UsuariosDAO = new application.app.models.UsuariosDAO(connection); // passa a variável connMongoDb acima como parâmetro

UsuariosDAO.inserirUsuario(dadosForm);

res.send('Cadastrado com sucesso!');
};

User file. The error starts at line 6 of the code:

function UsuariosDAO(connection){
this._connection = connection(); // recebe a variável db do arquivo dbConnection
};

UsuariosDAO.prototype.inserirUsuario = function(usuario){
this._connection.open( function(err, mongoclient){
    mongoclient.collection("users", function(err, collection){
       collection.insert(usuario);


    });
});
};

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

For better view of the problem, follow error code:

TypeError: this._connection.open is not a function
at UsuariosDAO.inserirUsuario (c:\Users\micha\GitHub\Projetos-Praticos\Projeto-CRUD\app\models\UsuariosDAO.js:6:22)
at Object.module.exports.cadastrar (c:\Users\micha\GitHub\Projetos-Praticos\Projeto-CRUD\app\controllers\cadastro.js:23:17)
at c:\Users\micha\GitHub\Projetos-Praticos\Projeto-CRUD\app\routes\cadastro:7:46
at Layer.handle [as handle_request] (c:\Users\micha\GitHub\Projetos-Praticos\Projeto-CRUD\node_modules\express\lib\router\layer.js:95:5)
at next (c:\Users\micha\GitHub\Projetos-Praticos\Projeto-CRUD\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (c:\Users\micha\GitHub\Projetos-Praticos\Projeto-CRUD\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (c:\Users\micha\GitHub\Projetos-Praticos\Projeto-CRUD\node_modules\express\lib\router\layer.js:95:5)
at c:\Users\micha\GitHub\Projetos-Praticos\Projeto-CRUD\node_modules\express\lib\router\index.js:281:22
at Function.process_params (c:\Users\micha\GitHub\Projetos-Praticos\Projeto-CRUD\node_modules\express\lib\router\index.js:335:12)
at next (c:\Users\micha\GitHub\Projetos-Praticos\Projeto-CRUD\node_modules\express\lib\router\index.js:275:10)

I hope I have been able to explain the problem correctly. I would be very grateful!

  • Try implementing using Mongoose. https://www.npmjs.com/package/mongoose

  • I’ll give a study on this module, I’ve noticed that it is the most used for connection with the Mongodb bank. Anyway, if anyone knows, it would still help a lot to solve this problem with This, I believe it is a classic problem when using This, I think the solution may be using the bind function.

  • I did not analyze your code well because I saw that I was using the direct connection and I find it complicated to do this management. But if you think the problem is this. Do it like this: var self = this. Ready! Your this context will fix in self.

  • What would be the implementation of the code you thought? I tried to put the variable you said on line 6 of the code in the User file and on line 7 referenced it as self. _Connection.open..... but keeps giving the same error, says the self is not a function

  • vc assigned this value to self? var self = this;

  • If I understood the code, I saw that the problem is not in the this, and yes in the open. open does not exist in UsuariosDAO. To see that this project is on github, it will be better to pass link to see the full code. The community can help you better.

  • That’s it! I did exactly this way and returned the same error. This project is not on Github, what’s there is another similar one. But I started reading about Mongoose and I started to adopt it and it’s worked perfectly. So, I don’t think it’s interesting to continue in this code if this mongodb Node module isn’t used as much and Mongoose looks much more complete. I really appreciate the willingness to help and the recommendation of Mongoose q was very helpful.

Show 2 more comments
No answers

Browser other questions tagged

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