我有一个使用Node / Express / Mongo的应用程序,当我要编辑文档时遇到麻烦。我可以毫无问题地添加文档,但是当我构建“编辑”表单时,标题中出现了错误。我也可以提取文档并查看输入的信息。问题是当我尝试保存所做的任何更改时。
这是我的编辑功能:错误发生在FindByIdAndUpdate方法中的brief.brief_title = Updated_brief_title。
exports.postEditBrief = (req, res, next) => {
const briefId = req.body.briefId;
const updated_brief_title = req.body.brief_title;
const updated_country = req.body.country;
const updated_psg = req.body.psg;
const updated_one_year_withholding = req.body.one_year_withholding;
const updated_withholding_only = req.body.withholding_only;
const updated_practice_advisory = req.body.practice_advisory;
const updated_courthouse = req.body.courthouse;
const updated_pages = req.body.pages;
const updated_additional_psg = req.body.additional_psg;
const updated_gangs = req.body.gangs;
const updated_gang_name = req.body.gang_name;
const updated_link = req.body.link;
Brief.findByIdAndUpdate(briefId)
.then(brief => {
brief.brief_title = updated_brief_title;
brief.country = updated_country;
brief.psg = updated_psg;
brief.one_year_withholding = updated_one_year_withholding;
brief.withholding_only = updated_withholding_only;
brief.practice_advisory = updated_practice_advisory;
brief.courthouse = updated_courthouse;
brief.pages = updated_pages;
brief.additional_psg = updated_additional_psg;
brief.gangs = updated_gangs;
brief.gang_name = updated_gang_name;
brief.link = updated_link;
return brief.save();
})
.then(result => {
console.log(Brief);
res.redirect('/');
})
.catch(err => console.log(err));
};
我在Mongoose中使用了各种“查找和更新”方法,但是结果是相同的。
答案 0 :(得分:1)
您需要创建要更新的数据的object
并将其作为函数的第二个参数传递,当您执行.then()
时,它将获得正在执行的操作的结果而且您不需要在内部调用.save()
正确的版本应如下所示
exports.postEditBrief = (req, res, next) => {
const briefId = req.body.briefId;
let update = {
brief_title: req.body.brief_title,
country: req.body.country,
psg: req.body.psg,
one_year_withholding: req.body.one_year_withholding,
withholding_only: req.body.withholding_only,
practice_advisory: req.body.practice_advisory,
courthouse: req.body.courthouse,
pages: req.body.pages,
additional_psg: req.body.additional_psg,
gangs: req.body.gangs,
gang_name: req.body.gang_name,
link: req.body.link
}
Brief.findByIdAndUpdate(briefId, update)
.then(result => {
console.log(result);
res.redirect('/');
})
.catch(err => console.log(err));
};
您可以使用object destructuring
进一步简化它。
更新:
如果您不想覆盖文档,则需要将$set
与findOneandUpdate
一起使用
exports.postEditBrief = (req, res, next) => {
const briefId = req.body.briefId;
let update = {
brief_title: req.body.brief_title,
country: req.body.country,
psg: req.body.psg,
one_year_withholding: req.body.one_year_withholding,
withholding_only: req.body.withholding_only,
practice_advisory: req.body.practice_advisory,
courthouse: req.body.courthouse,
pages: req.body.pages,
additional_psg: req.body.additional_psg,
gangs: req.body.gangs,
gang_name: req.body.gang_name,
link: req.body.link
}
Brief.findOneAndUpdate(briefId, {$set:update})
.then(result => {
console.log(result);
res.redirect('/');
})
.catch(err => console.log(err));
};