user3264316
user3264316

Reputation: 332

node/mongodb - how to store queries' results

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

Upvotes: 0

Views: 117

Answers (1)

ejramire
ejramire

Reputation: 156

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

Upvotes: 1

Related Questions