sequelize / express-example

A proposal for the usage of Sequelize within an Express.JS application.
MIT License
2.5k stars 770 forks source link

How to update one object and get updated object as result? #55

Closed rusmichal closed 7 years ago

rusmichal commented 7 years ago

I update a user model like that

db.user.update({
            display_name: body.display_name,
            type: body.type,
            uri: body.uri,
            href: body.href,
            email: body.email,
            token: token,
            country: body.country,
          }, {
            returning: true,
            plain: true,
            limit: 1,
            where: {
                id: body.id
            }
        })

and I get a result:

[
  null,
  {
    "id": "asdasdasd",
    "display_name": "Michu",
    "type": null,
    "uri": "asdsd:asdasda",
    "href": "http://skadsda.pl",
    "email": "a@a.pl",
    "country": "PL",
    "createdAt": "2017-01-10T20:53:29.665Z",
    "updatedAt": "2017-01-11T16:29:06.591Z",
    "token": "eyJhbGciOiJIUzI1NiJ9.YXNkYXNkYXNk.rpEOsO5er5KHG3g7K9EAHWAMphOyxFsx-s1gtMJ4cAw"
  }
]

I want to get :

{
    "id": "asdasdasd",
    "display_name": "Michu",
    "type": null,
    "uri": "asdsd:asdasda",
    "href": "http://skadsda.pl",
    "email": "a@a.pl",
    "country": "PL",
    "createdAt": "2017-01-10T20:53:29.665Z",
    "updatedAt": "2017-01-11T16:29:06.591Z",
    "token": "eyJhbGciOiJIUzI1NiJ9.YXNkYXNkYXNk.rpEOsO5er5KHG3g7K9EAHWAMphOyxFsx-s1gtMJ4cAw"
  }

How to reach that simple stuff?!

sushantdhiman commented 7 years ago

Sequelize use Bluebird for promise implementation, you can use spread method and in 2nd paramter you will get updated object.

If you dont understand how Promise works consider reading this http://bluebirdjs.com/docs/why-promises.html

Please study Model API in docs for more information on return types and stuff

rusmichal commented 7 years ago

Thx.

My solution: // I use repository pattern

userRepo.findById(id).then(user => {
        if (user) {
            var token = jwt.sign(user.updatedAt, process.env.JWT_SECRET || "xxxxxxx");

            userRepo.updateById(req.body, token)
                .then(function(user) { return user; })
                .spread(function(user, updatedUser) {
                  res.status(201).send(updatedUser);
                })
                .catch(error => res.status(400).send(error));
        } else {
            userRepo.save(req.body)
                .then(user => res.status(201).send(user))
                .catch(error => res.status(400).send(error));
        }
    });