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

时间:2019-04-30 13:05:00

标签: javascript mongodb asynchronous es6-promise

我需要将我的第一个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请求中动态传递值。

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

1 个答案:

答案 0 :(得分: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'));
});