Utilizing Express and Handlebars for a user-defined value stored in the database.
Handlebars is configured to present "{{userMotto}}" as the value. Express carries out the following:
function validateUser(req, res, next) {
if (!req.user) {
res.render('index', {
user: req.user
});
} else {
currentUser = req.user.username;
userMottoCaught = fetchFromDatabase("motto", currentUser);
next();
}
}
The objective is to set "userMottoCaught" with the matching data from the database. The query used is:
function fetchFromDatabase(dbCollection, dbUID) {
this.dbCollection = dbCollection;
this.dbUID = dbUID;
return MongoClient.connectAsync(hiddenkeys.mongodbUri)
.then(function(db) {
return db.collection(dbCollection).findOneAsync({
_id: dbUID
});
})
.then(function(item) {
console.log("Found: ");
console.log(item);
return dbQueryResult;
})
.catch(function(err) {
//error handling
});
}
The challenge is extracting and returning the dbQueryResult back to the main function within queryDatabase. It seems stuck in a sub-function loop that prevents it from being returned properly. I've experimented with promises using Bluebird but remain unsure about the resolution. Callbacks have been considered too, yet seem complex to implement given my current code structure.
Upon rendering the page, the display method includes:
router.get('/', validateUser, function(req, res) {
res.render('dashboard', {
user: req.user,
userMotto: userMottoCaught
});
});
Presently, the output on the page reads: "Motto: [object Promise]", indicating a lapse in returning the correct value to the primary function.
Seeking guidance from anyone well-versed in these matters.
Cheers,
Dean