Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bookshelf js save() command not updating rows in postgresql db

JS beginner trying to get a PostgreSQL DB talking to express.js through bookshelf.js.

github: https://github.com/duskyshelf/bookers-academy/blob/master/booker.js

var knex = require('knex')({
  client: 'pg',
  connection: "postgres://localhost/bookers"
});

var bookshelf = require('bookshelf')(knex);

var User = bookshelf.Model.extend({
  tableName: 'users'
});

var bob = new User({id: 2});
bob.save()

bookshelf.js seems unable to add any content to the db.

Current error message is: "Unhandled rejection CustomError: No Rows Updated'

like image 778
David Upsdale Avatar asked Jul 13 '15 16:07

David Upsdale


1 Answers

When you create your model providing your own id, like in

var bob = new User({id: 2});

Bookshelf assumes it is an update operation, not an insertion. It sets the internal isNew attribute to false, and when save() is invoked, instead of INSERT INTO user(id, ...) VALUES (2, ...);, it executes UPDATE user ... WHERE id = 2;.

If there is no user with id = 2 the update will almost silently DO NOTHING.

To force an insert you must change the save() to:

bob.save(null, {method: 'insert'});

Bookshelf save() documentation describes this behavior.

like image 105
flaviodesousa Avatar answered Nov 04 '22 07:11

flaviodesousa