Javascript 使更新API动态化
小问题,我如何使这个API只从我的请求中获取define json键,而不使用Javascript 使更新API动态化,javascript,node.js,postgresql,api,sequelize.js,Javascript,Node.js,Postgresql,Api,Sequelize.js,小问题,我如何使这个API只从我的请求中获取define json键,而不使用if语句检查请求中的每个键,如下所示: const updateArticle = async (req, res) => { const { title, description, body } = req.body; try { const article = await Article.findByPk(req.params.id); if (title) article.titl
if语句检查请求中的每个键,如下所示:
const updateArticle = async (req, res) => {
const { title, description, body } = req.body;
try {
const article = await Article.findByPk(req.params.id);
if (title) article.title = title;
if (description) article.description = description;
if (body) article.body = body;
await article.save();
res.json("Article updated.");
} catch (err) {
console.log(err);
}
};
您可以使用Object.assign()
方法将源对象的属性覆盖到目标对象
const updateArticle=async(请求、恢复)=>{
const{title,description,body}=req.body;
试一试{
const article=await article.findByPk(req.params.id);
分配对象(条款、请求正文);
等待文章。保存();
res.json(“文章更新”);
}捕捉(错误){
控制台日志(err);
}
};