Friday, 17 March 2017

Why nodejs is not connecting mongo?

I have this code in node:

"use strict"
var MongoClient = require('mongodb').MongoClient;

var UserGateway = function(mongoURL) {
  this.mongoURL = mongoURL;
}

UserGateway.prototype.connect = function() {
   return new Promise((resolve, reject)=>{
      MongoClient.connect(mongoURL, function(err, db) {
        if(err) {
           reject(err);
        }
        resolve(db);
   });
});
}

UserGateway.prototype.getUsername = function(_userId) {
   return new Promise((resolve, reject)=>{
      connect().then((db) => {

       let user = db.collection('user').findOne({"_id":_userId});
       disconnect();
       resolve(user);
   });
  });
}

UserGateway.prototype.disconnect = function() {
  return new Promise((resolve, reject) => {
    MongoClient.close(function(err, db) {
      if(err) {
        reject(err)
      }
      resolve(db)
    })
 })
}

module.exports = UserGateway;

And i execute it with:

var UserGateway = require("./src/userGateway.js")

var userGT = new UserGateway("mongodb://localhost:27017/UserSports")
userGT.getUsername(1).then(userName => {
   console.log(userName)
})

Anyone has an idea where the error is? I've been programming in js so little. My idea was to connect to mongo and retrieve a username giving the user Id, and to let getUsername manage the connect and disconnect.



via Erinel

No comments:

Post a Comment