tree em
tree em

Reputation: 21711

How can I pass the return value from mongo query to express template

I am trying to create a helper function to use in the template.

var User = require("../models/user");
var ObjectId = require('mongodb').ObjectID;

function retrieveUser(id, callback) {
    User.find(ObjectId(id), {image: 1, _id: 0}, function(err, users) {
      if (err) {
        callback(err, null);
      } else {
        callback(null, users[0]);
      }
    }).lean();
  };
function getUserImage(id){
    user_image = null;
    retrieveUser(id, function(err, user) {
        if (err) {
            console.log(err);
        }
        console.log(user.image);
        user_image = user.image
        // do something with user
    });
  return user_image;
}

module.exports.getUserImage = getUserImage;

I see the correct value in the console.log , But when I call this

<%=getUserImage("5d999578aeb073247de4bd6e")%>

home.ejs for example is give me undefined.

How should I create the this helper in the right way?

Upvotes: 0

Views: 52

Answers (1)

Vikash Kesarwani
Vikash Kesarwani

Reputation: 850

It is happening because retrieveUser is an asynchronous function so the return user_image statement does not wait for retrieveUser to complete. You can use synchronous version of this function (if exists) or you should first call and collect user_image before calling the render function and pass it to the render function in your route. In my opinion, keeping in mind the asynchronous nature of JavaScript, the 2nd approach is write way to go.

You can write your middleware to look something like this -

    (req, res, next) => {
     retrieveUser(<ID>, function(err, user) {
        if (err) {
            console.log(err);
        }
        res.render('view_name', { image: user.image });
    });
}

This is only a pseudo code you can use this concept in your code however you like. Just remember that render must be called in the callback function.

Upvotes: 1

Related Questions