mongodb - Node Express Trouble returning object to view from query -


i'm trying to:

  1. pass user's id model query, should return user record mongo.
  2. render user object view can use fields.

i'm not quite sure what's going wrong - query function finds correct user , can console.dir see fields. when try return view res.render nothing:

here's route:

app.get('/account', function(req, res) {   res.render('account', {title: 'your account', username: req.user.name, user:account.check(req.user.id)  });  }); 

and query function:

exports.check = function(userid) {  mongoclient.connect('mongodb://127.0.0.1:27017/test', function(err, db) { if(err) throw err; var collection = db.collection('test');  collection.findone({userid : userid}, function(err, user) { if (err) throw err;  console.log("account.check logging found user console: "); console.dir(user);  return user;      });  });     } 

again, shows proper entry

finally view:

<h1>account page</h1> <hr> <p>why, hello, there <b> {{username}} </b> </p><br/>  <p>you came {{user.provider}}</p>  <p>{{user.lastconnected}}</p>  <a href="/">go home</a> ~ <a href="logout">log out</a> 

any held appreciated!

the mongodb findone function asynchronous (it takes callback argument). means check function needs asynchronous , take callback argument (or return promise).

then should call res.render() inside callback pass query on success.

app.get('/account', function(req, res) {    account.check(req.user.id, function(error, user) {     if (error) {       // smart res.status(500).end()       return;     }     res.render('account', {title: 'your account', username: req.user.name, user:user });     }  }); 

and check function should like:

exports.check = function(userid, callback) {    mongoclient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {     if(err) {        callback(err);     }      var collection = db.collection('test');      collection.findone({userid : userid}, function(err, user) {       if(err) {         callback(err);       }        console.log("account.check logging found user console: ");       console.dir(user);         callback(null, user);     });   });     } 

of course if don't need additional processing, can pass callback argument callback collection.findone(). kept way because closer doing initially.


Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -

php - Accessing static methods using newly created $obj or using class Name -