2017-02-14 22 views
1

創建一個基本的express.js應用程序並添加了一個模型(使用thinky和rethinkdb)嘗試將變更饋送傳遞給玉文件,但無法確定如何傳遞饋送結果。我的理解是,changes()返回無限光標。所以它總是在等待新的數據。如何處理快遞資源。任何想法我在這裏想念什麼?使用thinky在Express.js中進行Rethinkdb變更

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

,我相信你所面對的問題是,feed.each是要求進料中所含的每個項目所包含的功能的迴路。因此,要訪問console.log(doc)中包含的doc,您需要將代碼置於doc存在的函數中(位於變量doc的範圍內),或者您需要創建一個全局變量來存儲doc值(S)。

因此,例如,假設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; 
+0

嗨穆罕默德,我很欣賞花時間回答我的問題,但它沒有奏效。 doc仍未定義。我將不得不考慮整合socket.io以將其傳遞到前端。我希望Express.js下一個版本會考慮來自db的實時更新。每個新框架都應該考慮一個重要特徵。 – Marco

+0

@marco如果你在res.render之前添加console.log MYDOCS,你會得到一個輸出嗎? –

+0

是的。但那是我以前的同樣的問題。 – Marco

相關問題