I'm working to create an MVC on top of expressjs, in order to learn express. I am having trouble between the model and view. The Git repo exists here.
I would like to display a list of blog posts. I'm using a custom jasmine view, in conjunction with mongoose and expressjs. I have no idea how to return the list of posts from the query (find({}) and transfer that object to the view or work with those posts in jasmine once I have them.
The best idea I had to access this information in my view was through res.locals, but it doesn't seem to work.
// read
app.get('/', function(req, res){
Blog.find({},function(err, records){
res.locals.posts = records
// res.send(records);
records.forEach(function(record){
console.log(record["body"])
});
});
res.render("home.jade", {online:req.online.length + ' users online', posts:VARIABLE_I_AM_UNCLEAR_ABOUT});
});
I can see body text in my console.log, so its clear I have json blog posts. Furthermore I can return JSON with res.send(records). I would like access to those records, so I can style those in my view with jasmine.
Just move the render to the location where you tried send:
app.get('/', function(req, res){
Blog.find({},function(err, records){
res.render("home.jade", {
online : req.online.length + ' users online',
posts : records
});
});
});
Blog.find() is asynchronous, so the callback function will get called only when the results are sent back from the database. In your original situation, you rendered the template without first waiting for the results.