如何 return 来自猫鼬模式的布尔值 find() - 基于找到的属性

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

我正在尝试将用户定向到适当的页面(在首选项流程完成之前限制对主页的访问)。当我调用 preferencesFlowCompleted(req, next) 时,我希望 Boolean 值被 return 编辑,但是我得到的是 Promise {undefined}。因此,我的家庭路线不受限制,因为 Promise {undefined} 计算为 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');
    }
};

有人知道在这种情况下我如何 return Boolean 吗?

/**
 * 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;

首先,你必须正确使用'async/await'。我目前没有安装 mongo,但试试这个:

/**
 * 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');
    }
};

和:

/**
 * 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;