【问题标题】:Rethinkdb changesfeed in Express.js using thinky使用 thinky 在 Express.js 中重新思考数据库更改提要
【发布时间】:2017-07-03 08:17:34
【问题描述】:

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

    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;

【问题讨论】:

    标签: javascript node.js express scope thinky


    【解决方案1】:

    我相信您面临的问题是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;
    

    【讨论】:

    • 嗨,Mohammad,我很高兴花时间回答我的问题,但它没有用。文档仍然未定义。我将不得不查看集成 socket.io 以将其传递到前面。我希望 Express.js 的下一个版本会考虑数据库的实时更新。这是每个新框架都应该考虑的重要特性。
    • @marco 如果你在 res.render 之前添加 console.log MYDOCS,你会得到输出吗?
    • 是的。但这与我之前遇到的问题相同。
    • 我想我可能误解了这个问题。您是否尝试将应用程序生命周期的所有更改添加到 res 中?还是只是页面请求期间发生的更改?
    • 是的,应用程序的生命周期(实时更新被推送到用户仪表板)不在页面请求期间。我的错。没有解释最终目标。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-15
    • 1970-01-01
    • 2015-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多