I'm trying to get data from a document in RethinkDB in NodeJS and pass the result into a variable I wish to use in a template file, but it is always undefined
when I try to print the data
variable like #{data}
(I'm using pug/jade) because it's an asynch call (i think).
'use strict';
var r = require('rethinkdb');
module.exports = function IndexModel() {
data: {
r.connect({host: '127.0.0.1', port: 28015}, function(err, conn) {
r.db('mydb').table('mytable').run(conn).then(function(cursor) {
cursor.toArray(function(err, result) {
if (err) throw err;
return JSON.stringify(result, null, 2);
});
});
});
}
};
I figured it must be because nodejs want it to be an object, so I tried to parse it like JSON.parse(JSON.stringify(result, null, 2))
but that throws the same error.
When I do console.log(JSON.stringify(result, null, 2))
it prints this after the error.
[
{
"id": "307ad5e9-a0db-461b-a564-081d73f9b34f",
"title": "hello"
}
]
This is the exact error if its needed:
Cannot read property 'length' of undefined
at eval (eval at wrap (C:\Users\Me\Project\node_modules\pug-runtime\wrap.js:6:10), <anonymous>:248:32)
at eval (eval at wrap (C:\Users\Me\Project\node_modules\pug-runtime\wrap.js:6:10), <anonymous>:379:4)
at template (eval at wrap (C:\Users\Me\Project\node_modules\pug-runtime\wrap.js:6:10), <anonymous>:389:211)
at Object.exports.renderFile (C:\Users\Me\Project\node_modules\pug\lib\index.js:427:38)
at Object.exports.renderFile (C:\Users\Me\Project\node_modules\pug\lib\index.js:417:21)
at View.exports.__express [as engine] (C:\Users\Me\Project\node_modules\pug\lib\index.js:464:11)
at C:\Users\Me\Project\node_modules\engine-munger\index.js:133:22
at C:\Users\Me\Project\node_modules\engine-munger\index.js:154:17
at C:\Users\Me\Project\node_modules\engine-munger\index.js:87:21
at C:\Users\Me\Project\node_modules\engine-munger\index.js:189:13
at FSReqWrap.oncomplete (fs.js:153:5)
Any idea how I can solve this everlasting problem? Thanks!
Edit:
It appears that I can not return anything from the data
variable inside any rethinkdb connection or promise, it has to be outside of it to get detected.