3

I want to update my database if the key of the request exists.

this is my update action:

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

For example, I want to update the name column if req.body.name is not empty. What is the shortest way to do this?

ProgrammerPer
  • 1,125
  • 1
  • 11
  • 26
S.M_Emamian
  • 17,005
  • 37
  • 135
  • 254

3 Answers3

2

Here you go :

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

Or you can use Remove blank attributes from an Object in Javascript , and use that value for updating model

And then just simply :

shopsModel.Shop.update(request,...);

NOTE :

As I can see that key name and req.body names are almost same , so you can directly use

let request = req.body;
Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122
1

Try below with use of nullish coalescing:

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

It provides returning only keys you want to update and as a result changing only those columns in DB.

You can create a helper function for it:

const  returnIfNotNil = key => key ?? undefined

and use as above

    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)
    })

or make even more consistent (assuming you use all body to update):

// get only defined fields
const getOnlyDefinedFields = (body: Body) = Object.entries(body)
   .reduce((acc, [key, value]) => ({
      ...acc,
      [key]: returnIfNotNil(value) 
   }), {})
const data = getOnlyDefinedFields(req.body)

await shopsModel.Shop.update(data)
kmnowak
  • 804
  • 1
  • 8
  • 23
0

If you have your psql connection you can do simply like this:

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

replace table with your table name...
check this for more info: https://mherman.org/blog/postgresql-and-nodejs/ . (at update section)

V. Sambor
  • 12,361
  • 6
  • 46
  • 65