如何将一个mongodb请求的结果同步传递到下一个请求的值?

问题描述 投票:0回答:1

我需要将我的第一个MongoDB查询中获得的state.name值放入下一组MongoDB查询中。当我第一次查询console.log时,我实现了所需的结果,但在以下查询中显示为undefined。它是异步还是我错了?

我研究了将一个查询的结果传递到Express + MongoDB中的下一个查询以及查看Promises的示例 - 不确定我是否完全理解它。

// GET State Home
router.get('/:stateid', ensureAuthenticated, (req, res) => {
    const member = req.user;
    console.log(member);
    Promise.all([
        state = States.findOne({url:req.params.stateid}),
        statelegislation = StateLegislation.find({'state': state.name }),
        statepolicy = StatePolicy.find({'state': state.name }),
        stateregulation = StateRegulation.find({'state': state.name }),
        statelitigation = StateLitigation.find({'state': state.name }),
    ]).then(([state,statelegislation,statepolicy,stateregulation,statelitigation]) =>
        res.render('app/state/home', {
            state:state,
            statelegislation:statelegislation,
            statepolicy:statepolicy,
            stateregulation:stateregulation,
            statelitigation:statelitigation,
        }))
        .catch(err => res.send('Ops, something has gone wrong'));
});

在以下查询中传入字符串值而不是变量state.name时,我会获得该值的所需结果。

我无法从第一个MongoDB请求动态传递值。

任何和所有帮助表示赞赏!

javascript mongodb asynchronous es6-promise
1个回答
0
投票

你不能在一个Promise.all中立刻做到这一点。在开始剩余查询之前,您需要先等待state承诺:

router.get('/:stateid', ensureAuthenticated, (req, res) => {
    const member = req.user;
    console.log(member);
    States.findOne({url:req.params.stateid}).then(state =>
        Promise.all([
            StateLegislation.find({'state': state.name }),
            StatePolicy.find({'state': state.name }),
            StateRegulation.find({'state': state.name }),
            StateLitigation.find({'state': state.name }),
        ]).then(([statelegislation,statepolicy,stateregulation,statelitigation]) =>
            res.render('app/state/home', {
                state,
                statelegislation,
                statepolicy,
                stateregulation,
                statelitigation,
            })
        )
    )
    .catch(err => res.send('Ops, something has gone wrong'));
});
© www.soinside.com 2019 - 2024. All rights reserved.