CJ Thompson CJ Thompson - 4 months ago 13
Node.js Question

BookshelfJS: all ints are being returned as strings [pg]

bool
seems to work as expected, as does
json
type (postgres), but all of my id cols populate as strings (breaking the front-end code)

Is there a way to a. fix it, or b. tell bookshelf that that field is an integer?

Update

By request, here's some code snippets. I'm just testing the waters with node/bookshelf, so this isn't complicated code; it's mostly right out of the getting started guide. The database is an existing one we've been using for 2ish years, the
id
cols are definitely
int
for all tables

One good example, Calendars and

var Appointment = bs.Model.extend({
tableName: 'ec__appointments',
});

var Calendar = bs.Model.extend({
tableName: 'ec__calendars',

appointments: function() {
return this.hasMany(Appointment, 'calendar_id');
},
});


For this one, the calendar ids come down as
int
, but when I
fetch({withRelated:['appointments']})
, the
appointment.id
is a string.

{
"calendars": [
{
"id": 2,
"name": "Default Calendar",
"created_at": "2015-03-06T09:35:58.000Z",
"updated_at": "2016-03-23T03:28:07.000Z",
"appointments": [
{
"id": "107",
"calendar_id": "2",
"name": "Test",
"starts_at": null,
"ends_at": null,
"created_at": "2015-05-29T23:13:20.000Z",
"updated_at": "2015-05-29T23:13:20.000Z",
},

Answer

You can fix this problem with the following code:

var pg = require('pg');
pg.types.setTypeParser(20, 'text', parseInt);

More details here: https://github.com/tgriesser/knex/issues/387