【问题标题】:How do I pass in the result of one mongodb request synchronously into the value of the next request?如何将一个mongodb请求的结果同步传入下一个请求的值?
【发布时间】:2019-04-30 21:47:58
【问题描述】:

我需要将从我的第一个 MongoDB 查询中获得的 state.name 值放入下一组 MongoDB 查询中。当我 console.log 我的第一个查询时,我达到了预期的结果,但它在以下查询中显示为未定义。是它们是异步的还是我传错了?

我研究了在 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】:

    你不能在一个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'));
    });
    

    【讨论】:

    猜你喜欢
    • 2018-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多