与猫鼬异步等待返回空对象 [英] Async Await with Mongoose Returns Empty Object
问题描述
我有一个用于用户个人资料的猫鼬模式,他们可以在其中添加工作经验(当前为模式中的对象数组).
I have my mongoose schema for a user's profile where they can add work experience (currently an array of objects in schema).
我已使用以下代码查找用户的个人资料,并获得experience对象作为输入,然后将其附加到架构中的数组,并返回具有经验的保存的个人资料:
I have used the following code to find the user's profile and get the experience object as input then attach it to the array in schema and return the saved profile with experience:
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,但我想尝试一种新的做事方式.
The problem here is that the response is always an empty object and when I check my database, there is no experience saved. Is this code wrong? Same thing works with Promises but I want to try a new way of doing things.
推荐答案
async-await
模式是编写 Promise
的另一种方法,该函数的返回值为整个异步的 Promise.resolve(结果)
或 Promise.reject(原因)
.
The async-await
pattern is another way to write Promise
, the return value of the function is Promise.resolve(result)
or Promise.reject(reason)
of the whole async.
在外部函数(在这种情况下为 Router.post
)中,它必须使用 async-await
或 then
Promise 模式,以处理返回的 Promise
.否则, async
函数将没有机会运行,因为返回的 Promise
将被省略.
In the outer function, Router.post
in this case, it has to use async-await
, or then
of Promise
pattern, to deal with the returned Promise
. Orelse, the async
function would not have chance to run, as the returned Promise
would be omitted.
这篇关于与猫鼬异步等待返回空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!