Created a basic express.js application and added a model (using thinky and rethinkdb) trying to pass the changesfeed to the jade file and unable to figure how to pass the results of the feed. My understanding is that changes() returns infinite cursor. So it is always waiting for new data. How to handle that in express res. Any idea what am I missing here?
var express = require('express');
var router = express.Router();
var thinky = require('thinky')();
var type = thinky.type;
var r = thinky.r;
var User = thinky.createModel('User', {
name: type.string()
});
//end of thinky code to create the model
// GET home page.
router.get('/', function (req, res) {
var user = new User({name: req.query.author});
user.save().then(function(result) {
console.log(result);
});
//User.run().then(function (result) {
//res.render('index', { title: 'Express', result: result });
//});
User.changes().then(function (feed) {
feed.each(function (err, doc) { console.log(doc);}); //pass doc to the res
res.render('index', { title: 'Express', doc: doc}) //doc is undefined when I run the application. Why?
});
});
module.exports = router;
The problem that I believe you are facing is that
feed.each
is a loop that is calling the contained function for each item contained in the feed. So to access thedoc
contained inconsole.log(doc)
you are going to need to either place your code in the function in whichdoc
exists(is in the scope of the variabledoc
), or you are going to need to make a global variable to store doc value(s).So for example, assuming
doc
is a string and that you wish to place alldoc
's in an array. You would need to start off by creating a variable which has a scope thatres.render
is in, which for this example will beMYDOCS
. Then you would need to append each doc to it, and after that you would simply use MYDOC anytime you are attempting to access a doc outside of thefeed.each
function.