0

Could somebody smart explain me using my example how nodejs works? It drives me crazy. I dont want to call always the same function because I achived what I wanted but it is stupid and dirty solution.

var self = this;
MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  db.collection("myUsers").findOne({alexaUserID:userID}, function(err, result) {
    if (err || result==null){
        self.emit(':ask',
                SpeechOutputUtils.pickRandom(self.t('WELCOME'))
            );
        }
    else {
        console.log(result);
        self.emit(':ask',
                SpeechOutputUtils.pickRandom(self.t('WELCOME_OK', result.userName))
            );
    }
    db.close();
  });
});  

I wish I get my username (or anything from my mongodb) from a function

Im in my main file index.js

    const DbConn = require('../utils/db.utils');
    var userID = this.event.session.user.userId;
    var myName = "";
    myName = DbConn.dbFind("myUsers", userID);
    console.log(myName);

I should see Anna but I always see undefined

db.utils file:

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://*******/heroku_06r";

module.exports = {
    dbFind: function(collection, userID) {

        MongoClient.connect(url, function(err, db) {
              if (err) throw err;
              db.collection(collection).findOne({alexaUserID:userID}, function(err, result) {
                if (err || result==null){
                    return null;
                }
                else {
                    return result.userName;
                }
                db.close();
              });
            });  
    }

};
3
  • Is userID defined?
    – J. Titus
    Oct 24, 2017 at 17:56
  • Yes, How do you program with node.js if you can not get data from a function. Im confused
    – Anna K
    Oct 24, 2017 at 17:59
  • Thank you Mark_M, Kevin B... very nice of you!! ;/
    – Anna K
    Oct 24, 2017 at 18:11

0

Browse other questions tagged or ask your own question.