javascript - Rethinkdb 使用 thinky 更改 Express.js 中的 feed

标签 javascript node.js express scope thinky

创建了一个基本的express.js应用程序并添加了一个模型(使用thinky和rethinkdb)尝试将changefeed传递到jade文件,但无法弄清楚如何传递feed的结果。我的理解是,changes() 返回无限光标。所以它总是在等待新的数据。如何在 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 是一个字符串,并且您希望将所有 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;

关于javascript - Rethinkdb 使用 thinky 更改 Express.js 中的 feed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42236362/

相关文章:

javascript - JS 流 : What is the most clean and concise way to define an enum that is also treated like a type

node.js - 是否可以使用 SAML2 在 ReactJs 应用程序中实现 SSO?如果可能怎么办?

javascript - 'ng new my-app' 错误

node.js - mime.lookup 不是在 docker 内运行的expressjs中的函数

javascript - JSONP ajax 回调失败

javascript - 文件读取器速度慢且未在 React 上设置状态

mongodb - 无法获取/express.js 路由

node.js - React 前端连接到我计算机上的开发服务器,而不是托管在 Azure VM 上的 Node 服务器,为什么使用 localhost

javascript - 通过 AngularJS 加载时,动画 GIF 无法在 Firefox 中播放

node.js - HAProxy、Nginx 和 Node.js SPDY 终止