areller
areller

Reputation: 5238

Wait for mongoose to fetch user data to inject into locals

I am making a web application in which the user is expected to authenticate. I create a global variable(app.locals) which indicates whether the user is authenticated or not

app.use('/', function (req, res, next)
{
    app.locals.logedIn = req.session.user_id !== undefined;
    next();
});

So far everything works fine. The problem begins when i try to inject a user object for authenticated users:

app.use('/', function (req, res, next)
{
    app.locals.logedIn = req.session.user_id !== undefined;

    if (app.locals.logedIn)
    {
        mongoose.model('users').findById(req.session.user_id).exec(function (err, user)
        {
            app.locals.user = user;
        });
    }
    else
    {
        app.locals.user = null;
    }

    next();
});

whenever i try to access the user global remotely (in a template for instance), it fails and says that the user variable is null.

I figured that i happens because i don't wait for the user object to be injected into the locals.

Is there a way to wait for the mongoose query to finish?

mongoose.model('users').findById(req.session.user_id).exec(function (err, user)
{
    app.locals.user = user;
}).wait();

^^ Like that for instance...

Or maybe i should just change my approach?

The thing is that i want a user object that can be accessed from templates in order to render information about the user.

Thank you, Arik

Upvotes: 0

Views: 135

Answers (1)

Louay Alakkad
Louay Alakkad

Reputation: 7408

You need to put the next() bit inside the exec callback.

app.use('/', function (req, res, next)
{
    app.locals.logedIn = req.session.user_id !== undefined;

    if (app.locals.logedIn)
    {
        mongoose.model('users').findById(req.session.user_id).exec(function (err, user)
        {
            app.locals.user = user;
            next();
        });
    }
    else
    {
        app.locals.user = null;
        next();
    }
});

Upvotes: 2

Related Questions