user2001702
user2001702

Reputation:

Using async / await with mongoose.js

Looking for help to rewrite these 2 queries using async / await instead of using the nested callbacks approach.

exports.post_edit_get = function(req, res, next) {
    var id = req.params.id;
    if (mongoose.Types.ObjectId.isValid(id)){
        POST.findById(id, function (err, doc){
            if (err) { return next(err); }
            playerQuery.exec(function (err, players){
                if (err) { return next(err); }
                res.render('posts/posts_admin', { title: pageTitle, formData: doc, players: players });
            });
        });
    }else{
        res.send("Invalid ID");
    };
};

Upvotes: 0

Views: 2092

Answers (1)

Renato Gama
Renato Gama

Reputation: 16519

Here you go

const { isValid } = mongoose.Types.ObjectId

exports.post_edit_get = async function(req, res, next) {
    var { id } = req.params;

    if (!isValid(id)){
        return res.send("Invalid ID");        
    }

    try {
        const post = await POST.findById(id)
        const players = await playerQuery.exec()

        res.render('posts/posts_admin', { 
            title: pageTitle, 
            formData: doc, 
            players: players 
        })
    } catch (err) {
        return next(err)        
    }
}

If you want to get rid of these try/catches at the route handler level you'll want to have a look at this post; Using async/await to write cleaner route handlers

Upvotes: 2

Related Questions