0

I'm using Express.js and I have this simple router

router.get('/', function(req, res) {
    var userlist;
    req.db.get("usercollection").find({},{})
        .success(function(docs){
            userlist = docs;
        });

    res.render('index', { title: 'Express' , userlist: userlist});
});

but nothing's going into userlist. I know that writing the above as

router.get('/', function(req, res) {
    req.db.get("usercollection").find({},{})
        .success(function(docs){
            res.render('index', { title: 'Express' , userlist: docs});
        });
});

will work, but I'd like to know why the previous does not work. Also, what does db.get(...).find() return? Does it return the same as "docs" in the later code?

Thanks very much

user3264316
  • 332
  • 3
  • 18

1 Answers1

1

This is because req.db.get().find() is an asynchronous function. "res.render" may be happening before the userlist=docs assignation.

ejramire
  • 156
  • 1
  • 6
  • So how would I do if I wanted to render multiple collection sets? – user3264316 Jun 21 '14 at 21:51
  • I see 2 options: Making a big query that gets all the documents you need, "organize" them server side and then sending them to render, or nesting multiple queries. I think the second option is better. – ejramire Jun 21 '14 at 21:59
  • That seems fairly complicated. Maybe an alternative would be to get the queries I need via AJAX calls (to a restful api, for example) on page load? – user3264316 Jun 21 '14 at 22:03
  • 1
    You can do that too. However, depending on the relationship between your collections, you can do things like "populate"(in case you're using Mongoose) for example. – ejramire Jun 21 '14 at 22:24