Reputation: 1955
//posts
var docs, cats;
var db = req.db;
var catcollection = db.get('catcollection');
var postcollection = db.get('postcollection');
// find all post
postcollection.find({},{},function(e,docs){
console.log('posts ---> '+util.inspect(docs));
}); // end find all post
catcollection.find({},{},function(e,catss){
cats=catss;
console.log('cats --> '+util.inspect(cats)); //<<<---- write objects from mongo
}); // end find all cats for select
res.render('newpost', {
posts : docs, cats:cats, title: 'Add New post'});
}); **//<<<---it didn't passing the cats:cats and post vars to jade **
jade template
extends layout
block content
h1= title
form#formAddPost(name="addpost",method="post",action="/addpost")
input#inputPostTitle(type="text", placeholder="posttitle", name="posttitle")
textarea#inputPostTitle(placeholder="postdesc", name="postdesc")
textarea#inputPostTitle(placeholder="posttext", name="posttext")
select#selectPostCats(placeholder="postdesc", name="posttext")
each cat, i in cats
option(value="#{cat._id}") #{cat.titlecat}
button#btnSubmit(type="submit") submit
ul
each post, i in posts
li= i+" "
a(href="/editpst/#{post._id}")=#{post.title}
I get this error message in jade tpl Cannot read property 'length' of undefined
but if I wrote
catcollection.find({},{},function(e,catss){
cats=catss;
console.log('cats --> '+util.inspect(cats));
**res.render('newpost', {
cats:cats, title: 'Add New post'});**
}); // end find all cats for select
It passing category list to jade , but i can't pass post list to jade. How to passing few variables (posts and cats ) to jade tpl?
Upvotes: 2
Views: 165
Reputation: 191809
Both of the .find
s execute asynchronously so you don't know when (or if) either one will complete. That is to say you need to wait until both of the callbacks are called before you attempt to render the template.
The simplest way in your current implementation would be to nest everything:
postcollection.find({},{},function(e,docs){
// handle errors
catcollection.find({},{},function(e,cats){
res.render('newpost', {
posts : docs, cats:cats, title: 'Add New post'});
});
});
});
However you can do these queries simultaneously because they do not depend on each other. The best way to do that is to probably use promises.
Promise.all([postcollection.find(), catcollection.find()])
.then(function (docs, cats) {
res.render('newpost', {
posts : docs, cats:cats, title: 'Add New post'});
});
});
This assumes that .find
returns a promise. It should for the current Mongo driver.
Upvotes: 2