Reputation: 1429
How to insert a increment method like bookshelf.knex('articles').increment('fetchCount', 1)
in the code below:
router.get('/:id', (req, res) => {
Article.query({
where: {id: req.params.id}
}).fetch().then(article => {
res.json(article)
})
})
I have a table called 'articles', and I want to increment a value in a fetchCount column before it send json response.
when I use bookshelf.knex, bookshelf should be my model like Article?
Upvotes: 2
Views: 349
Reputation: 7815
Bookshelf way is something like:
router.get('/:id', (req, res) => {
Bookshelf.transaction(trx => {
return Article
.query({
where: {id: req.params.id}
})
.fetch({transacting: trx})
.then(article => {
// handle article == null here
return article
.save(
{fetchCount: 1 + article.get('fetchCount')},
{patch: true, transacting: trx})
})
})
.then(article => {
res.json(article)
})
})
The main point is having the transaction on both fetching and updating, so ensuring the value is locked and consistent until updated.
Upvotes: 2