如果密钥存在,如何更新-序列化

时间:2018-11-06 07:20:03

标签: javascript node.js postgresql sequelize.js

如果请求的密钥存在,我想更新数据库。

这是我的更新操作:

      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,
        ...

例如,如果name不为空,我想更新req.body.name列。 最简单的方法是什么?

3 个答案:

答案 0 :(得分:1)

您在这里:

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,...);
  

注意:

     

正如我所看到的,键名和req.body名称几乎相同,因此您   可以直接使用

let request = req.body;

答案 1 :(得分:0)

如果您拥有psql连接,则可以像这样简单地进行操作:

if(req.body.name) {
    client.query('UPDATE table SET name=($1)', [name]);
}

用表名替换表...
请检查此以获取更多信息:https://mherman.org/blog/postgresql-and-nodejs/。 (在更新部分)

答案 2 :(得分:0)

尝试以下方法:

shopsModel.Shop.update({
name: req.body.name || undefined,
province: req.body.province || undefinedv,
city: req.body.city || undefined,
address: req.body.address || undefined,
username: req.body.username || undefined,
type: req.body.type || undefined
})

它仅返回要更新的键,因此仅更改数据库中的那些列。

您可以为其创建自定义功能

const  returnIfNotNil = key => key || undefined

并按上述使用

shopsModel.Shop.update({
name: returnIfNotNil(req.body.name),
province: returnIfNotNil(req.body.province),
city: returnIfNotNil(req.body.city),
address: returnIfNotNil(req.body.address),
username: returnIfNotNil(req.body.username),
type: returnIfNotNil(req.body.type)
})

或者使之更加一致(假设您全身用尿布过腹):

shopsModel.Shop.update(req.body.map(key => returnIfNotNil(key)))

甚至更好:

shopsModel.Shop.update(req.body.map(returnIfNotNil))