mongoose等待承诺错误

时间:2018-06-11 22:29:29

标签: javascript express mongoose

我正在尝试使用await查询集合但我无法运行它。我没有看到错误

router.route('/errors')
    .post((req, res) => {
        const envirementName = getProjectEnv(getErrorLocation(req.body.error));

        let envCollection = await EnvirementProjectsCollection.findOne({envirementName}).exec();
        console.log(envCollection);
    });

它崩溃了 -

let envCollection = await EnvirementProjectsCollection.findOne({envirementName}).exec();
                                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

SyntaxError: Unexpected identifier
    at createScript (vm.js:74:10)
    at Object.runInThisContext (vm.js:116:10)
    at Module._compile (module.js:588:28)

从我看到的查询的exec()函数将返回我想要等待的promise。目前我无法找到错误。我会很高兴得到一些解释,并帮助我做错了什么。

提前致谢!

1 个答案:

答案 0 :(得分:2)

我认为您在函数之前没有使用过异步关键字。

尝试使用此代码。

希望这个答案对你有所帮助。

router.route('/errors')
    .post(async (req, res) => {
        const envirementName = getProjectEnv(getErrorLocation(req.body.error));

        let envCollection = await EnvirementProjectsCollection.findOne({envirementName}).exec();
        console.log(envCollection);
    });