【发布时间】: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