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