Home > Net >  How to return a Boolean from Mongoose Schema find() - based on attribute found
How to return a Boolean from Mongoose Schema find() - based on attribute found

Time:10-13

I am trying to direct the user to the appropriate page (restricting access to home until the preferences flow has been completed). When I call preferencesFlowCompleted(req, next), I am expecting a Boolean value to be returned, however I am getting a Promise {undefined}. Consequently, my home route is not restricted since Promise {undefined} evaluates to true.

/**
 * Get home page.
 * @param {*} req 
 * @param {*} res 
 * @param {*} next 
 */
exports.getHome = (req, res, next) => {
    if (preferencesFlowCompleted(req, next)) {
        res.status(202).render('home');
    } else {
        res.redirect('/preferences');
    }
};

Does anyone know how I can return the Boolean in this case?

/**
 * Import schemas.
 */
const Preference = require('../models/preference');

async function preferencesFlowCompleted(req, next) {
    Preference.findOne({ userId: req.session.userId }, (err, preference) => {
        if (err) { return next(err); }
        if (preference) {
            return preference.completed; // this is a boolean attribute
        } else {
            return false;
        }
    });
};

module.exports = preferencesFlowCompleted;

CodePudding user response:

First of all, yo must use 'async/await' propertly. I don't have mongo currently installed but try this:

/**
 * Get home page.
 * @param {*} req 
 * @param {*} res 
 * @param {*} next 
 */
exports.getHome = async (req, res, next) => {
    if (await preferencesFlowCompleted(req, next)) {
        res.status(202).render('home');
    } else {
        res.redirect('/preferences');
    }
};

and:

/**
 * Import schemas.
 */
const Preference = require('../models/preference');

async function preferencesFlowCompleted(req, next) {
    try {
        const preference = await Preference.findOne({ userId: req.session.userId }); // maybe .exec() for better traces
        return preference ? preference.completed : false;
    } catch (err) {
        return next(err);
    }   
}     

module.exports = preferencesFlowCompleted;
  • Related