Rethinkdb changesfeed in Express.js 使用 thinky

Rethinkdb changesfeed in Express.js using thinky

创建了一个基本的 express.js 应用程序并添加了一个模型(使用 thinky 和 ​​rethinkdb)试图将 changesfeed 传递给 jade 文件,但无法确定如何传递 feed 的结果。我的理解是 changes() returns 无限游标。所以它总是在等待新数据。如何在 express res 中处理。知道我在这里想念什么吗?

    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;

我相信您面临的问题是 feed.each 是一个循环,它为提要中包含的每个项目调用包含的函数。因此,要访问 console.log(doc) 中包含的 doc,您需要将代码放在 doc 存在的函数中(在变量 doc 的范围内) ),或者您将需要创建一个全局变量来存储文档值。

例如,假设 doc 是一个字符串,并且您希望将所有 doc 放在一个数组中。您需要首先创建一个范围为 res.render 的变量,在本例中为 MYDOCS。然后您需要将每个文档附加到它,之后您可以在任何时候尝试访问 feed.each 函数之外的文档时简单地使用 MYDOC。

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;