How to update if key exists - sequelize

S.M_Emamian

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?

Vivek Doshi

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;

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

TOP Ranking

HotTag

Archive