Search code examples
javascriptnode.jsbookshelf.jsknex.js

Manually setting timestamp values in bookshelf.js


I have a table set up to have timestamps and bookshelf configured to use them. Normally everything happens as it should and bookshelf takes care of the timestamps, but I have a case where I want to specify them, but when I try to do that the values are ignored and the current date is used.

I've tried to simplify my use case down to the essentials:

var Author = Bookshelf.Model.extend({
  tableName: 'authors',
  hasTimestamps: ['created_at', 'updated_at'],

  bookAuthors: function(){
    return this.hasMany(require('.book_authors'));
  },

  associateBookWithAuthor(bookId,timestamp) {
    return self.related('bookAuthors').create({
      book_id: bookId,
      updated_at: timestamp, // ignored by bookshelf
      created_at: timestamp  // also ignored
    })
  }
}

I still want to keep the hasTimestamps configured for regular use cases. Is it possible to get Bookshelf to let me override the timestamps behavior?


Solution

  • Just updating right answer for new visitors to this question. The latest is bookshelf allows overriding timestamp values.

    See official documentation and example here

    https://bookshelfjs.org/api.html#Model-instance-hasTimestamps

    myModel.save({created_at: new Date(2015, 5, 2)}).then(function(updatedModel) {
      // {
      //   name: 'blah',
      //   created_at: 'Tue Jun 02 2015 00:00:00 GMT+0100 (WEST)',
      //   updated_at: 'Sun Mar 25 2018 15:07:11 GMT+0100 (WEST)'
      // }
    })