Reputation: 335
(This is my first question here, I'm excited :))
2 files: index.js (what I'm using to connect to the mongo, find and toArray the data), and admin.ejs where I want to display the data (user records: username, first name, last name...).
index.js:
var db = MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
if(err)
throw err;
db.collection("Users").find().toArray(function (err, result) {
var i, count;
for (i = 0, count = result.length; i < count; i++) {
myArr.push(result[i]);
}
myArr = JSON.stringify(myArr);
});
console.log(myArr); // just for testing
console.log("connected to the mongoDB !");
});
app.get('/', function (req, res) {
res.render('Admin', {
myVar: myArr
});
});
admin.ejs:
var myOtherVar = JSON.parse('<%-myVar%>');
In the broswer "view source code" I can see
var myOtherVar = JSON.parse('[{"_id":"567a6fd307200cb90f7af961","Username":"Yogev" ...
so I know that the data passes correctly, but any atempt to use it fails - the JS "see" it as object Object
and not as an array...
What should I do?
Upvotes: 2
Views: 1232
Reputation: 3559
This way you send a object to the view
res.view('Admin',{ myVar : myArr});
This way you use it in the view
<h1> <%= myVar[0].property %></h1>
In this case you use <%=
because <%
does not print the returned value by the expression just after it.
Upvotes: 0
Reputation: 1394
You'll just need to use object notation to access the data.
console.log(myOtherVar[0].Username)
// Returns 'Yogev'
Upvotes: 2