创建了一个基本的express.js应用程序,并添加了一个模型(使用thinky和rethinkdb),试图将changesfeed传递给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;发布于 2017-02-16 06:37:26
我相信您面临的问题是,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;https://stackoverflow.com/questions/42236362
复制相似问题