如果请求的键存在,我想更新我的数据库。
这是我的更新操作:
shopsModel.Shop.update({
name: req.body.name,
province: req.body.province,
city: req.body.city,
address: req.body.address,
username: req.body.username,
type: req.body.type,
...
例如,如果 req.body.name
不为空,我想更新 name
列。
执行此操作的最短方法是什么?
最佳答案
给你:
let request = {
name: req.body.name,
province: req.body.province,
city: req.body.city,
address: req.body.address,
username: req.body.username,
type: req.body.type,
...
}
// With the help of Lodash
request = _.pickBy(request, _.identity); // <--- Will remove empty | null | undefined
或者您可以使用 Remove blank attributes from an Object in Javascript ,并使用该值更新模型
然后只是简单地:
shopsModel.Shop.update(request,...);
NOTE :
As I can see that key name and
req.body
names are almost same , so you can directly uselet request = req.body;
关于javascript - 如果 key 存在,如何更新 - sequelize,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53167370/