How to update one object and get updated object as result?
rusmichal opened this issue · 2 comments
rusmichal commented
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
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
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));
}
});