【问题标题】:Async Await with Mongoose Returns Empty ObjectMongoose 的异步等待返回空对象
【发布时间】:2019-03-09 09:41:21
【问题描述】:

我有一个用户个人资料的猫鼬模式,他们可以在其中添加工作经验(目前是模式中的对象数组)。

我使用以下代码查找用户的个人资料并获取体验对象作为输入,然后将其附加到架构中的数组并返回已保存的个人资料和体验:

Router.post('/experience',
Passport.authenticate('jwt', {session: false}), async (req, res) => {
try {
    const myProfile = await Profile.findOne({user: req.user._id});

    if (myProfile) {
        const exp = {
            title: req.body.title,
            company: req.body.company,
            location: req.body.location,
            from: req.body.from,
            to: req.body.to,
            isCurrent: req.body.isCurrent,
            description: req.body.description
        };
        // add to Profile experience array
        Profile.experience.unshift(exp); // adds to beginning of array
        const savedProfile = await Profile.save(); // have also tried myProfile.save() but that doesn't work too
        if (savedProfile) {
            console.log(savedProfile);
            res.json({message: `Profile Updated Successfully`, details: savedProfile})
        }
        else { throw `Experience Details Not Saved`}
    }

} catch (err) { res.json(err); }
});

这里的问题是响应总是一个空对象,当我检查我的数据库时,没有保存任何经验。这段代码错了吗?同样的事情也适用于 Promises,但我想尝试一种新的做事方式。

【问题讨论】:

    标签: express async-await es6-promise


    【解决方案1】:

    async-await模式是Promise的另一种写法,函数的返回值为整个async的Promise.resolve(result)Promise.reject(reason)

    在外部函数中,Router.post在这种情况下,它必须使用async-await,或者Promise模式的then,来处理返回的Promise。 Orelse,async 函数将没有机会运行,因为返回的Promise 将被省略。

    【讨论】:

    • 是的,我熟悉 Promises。这里的问题是保存添加的体验对象时。我已经从 Profile.findOne() 记录了配置文件,但无法保存
    猜你喜欢
    • 2019-03-25
    • 2018-06-11
    • 2020-03-13
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-31
    • 2020-12-24
    • 2021-12-01
    相关资源
    最近更新 更多