diff --git a/lib/model.js b/lib/model.js index 8e1b98e6a765..22bb01ead46b 100644 --- a/lib/model.js +++ b/lib/model.js @@ -2480,7 +2480,7 @@ class Model { const now = Utils.now(this.sequelize.options.dialect); // Attach createdAt - if (createdAtAttr && !updateValues[createdAtAttr]) { + if (createdAtAttr && !insertValues[createdAtAttr]) { const field = this.rawAttributes[createdAtAttr].field || createdAtAttr; insertValues[field] = this._getDefaultTimestamp(createdAtAttr) || now; } diff --git a/test/integration/model/upsert.test.js b/test/integration/model/upsert.test.js index 2a67cb18e6c7..26e51c7bbc26 100644 --- a/test/integration/model/upsert.test.js +++ b/test/integration/model/upsert.test.js @@ -302,6 +302,15 @@ describe(Support.getTestDialectTeaser('Model'), () => { clock.restore(); }); + it('does not overwrite createdAt when supplied as an explicit insert value when using fields', async function() { + const clock = sinon.useFakeTimers(); + const originalCreatedAt = new Date('2010-01-01T12:00:00.000Z'); + await this.User.upsert({ id: 42, username: 'john', createdAt: originalCreatedAt }, { fields: ['id', 'username'] }); + const user = await this.User.findByPk(42); + expect(user.createdAt).to.deep.equal(originalCreatedAt); + clock.restore(); + }); + it('does not update using default values', async function() { await this.User.create({ id: 42, username: 'john', baz: 'new baz value' }); const user0 = await this.User.findByPk(42);