Rethinkdb changesfeed in Express.js using thinky

130 views Asked by At

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;
1

There are 1 answers

7
Mohammad Ali On BEST ANSWER

The problem that I believe you are facing is that feed.eachis a loop that is calling the contained function for each item contained in the feed. So to access the doc contained in console.log(doc) you are going to need to either place your code in the function in which doc exists(is in the scope of the variable doc), 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 all doc's in an array. You would need to start off by creating a variable which has a scope that res.render is in, which for this example will be MYDOCS. 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 the feed.each function.

var MYDOCS=[];
User.changes().then(function (feed){
    feed.each(function (err, doc) { MYDOCS.push(doc)});
});
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 });
    //});
        res.render('index', { title: 'Express', doc: MYDOCS[0]}) //doc is undefined when I run the application. Why?
    });
module.exports = router;