【发布时间】:2020-09-24 09:58:12
【问题描述】:
如何通过数组中的 ID 更新多个对象?我想通过用户的 ID 更新体验,
下面我附上了我的 mongodb json 对象截图:
我已经可以通过用户创建体验:
router.put('/experience',
[
auth,
[
check('title', 'Title is required').not().isEmpty(),
check('company', 'Company is required').not().isEmpty(),
check('from', 'From date is required').not().isEmpty(),
],
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const {
title,
company,
location,
from,
to,
current,
description,
} = req.body;
const newExp = {
title,
company,
location,
from,
to,
current,
description,
};
try {
const profile = await Profile.findOne({ user: req.user.id });
// unshift is same with push it pushes it in the beginner rather than the end
profile.experience.unshift(newExp);
await profile.save();
res.json(profile);
console.log(req.body);
} catch (err) {
console.error(err.message);
res.status(500).send('Send Error');
}
}
);
这是我关于更新的非工作代码strong text
router.patch('/experience/:exp_id', auth, async (req, res) => {
let id = req.params.exp_id;
let expId = req.body;
try {
const profile = await Profile.findOne({ user: req.user.id });
profile.experience.findOneAndUpdate(
{ id },
{ $set: { expId } },
{ new: true }
);
res.json(profile);
} catch (err) {
console.error(err.message);
res.status(500).send(err.message);
}
});
【问题讨论】:
-
在你的
findOneAndUpdate函数中使用id而不是{id}并使用{ $set:{ 'expId': expId,,,,,,,more fields if needed} }而不是{ $set: { expId } }。 -
它返回 profile.experience.findOneAndUpdate 不是一个函数我的 profile.experience 是一个对象数组顺便说一句。 user: { // 特殊字段类型,因为 // 它将关联到不同的用户类型:mongoose.Schema.Types.ObjectId, ref: 'user', }, experience: [ { title: { type: String, required: true , }, company: { type: String, required: true, }, location: { type: String, }, from: { type: Date, required: true, },