简体   繁体   中英

Passing MongoDB data to Jade view in ExpressJS

I have a question I hope you can help with. Basically, I'm doing a query on a MongoDB collection and attempting to pass the results back to a jade view.

app.helpers({
  clients: function(){
    users.find({uid:req.session.uid}).toArray(function(err, post){
      if(err){
        console.log(err);
      }else{
        return post;
      }
    });
  }
});

This is where I reference the helper object in the view

p #{clients}

Right now I'm just getting [object Object] as the value in the view. If I log the results, I'll get the expected document results but if I try to push it into an array or a var, I get the [object Object] result. Any ideas?

This won't work, because you use the following structure:

clients: function() {
    (some code)(function() {
        return variable;
    });
}

The return variable; statement returns from the inner function . But you need to return variable from the outer function . So how to do this? Actually you can't. You should do the query in a view and store the result for example in request and then pass the request variable to the template. You cannot use asynchronous functions in helpers.

Another thing is that when you use a function in a helper, then in the template you should use

p #{ clients() }

because it is a function. Nevertheless it won't work in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM