Sequelize: isNewRecord is always false

Viewed 2302

The issue

I have a Sequelize model called Test with an unique field: value (primary key). I'm using SQLite as database management system.

If I use ignoreDuplicates: true as option of bulkCreate() it's supposed to bulkCreate will ignore the new inserts if they exist on database. That works great, but all the objects of the array returned by the method bulkCreate() always have set the isNewRecord attribute to false, even when a new record was inserted on the database.

Code

const items = [ {value: 'a'}, {value: 'b'} ]; // Items to save on database.

const results = await Test.bulkCreate(items, {
    ignoreDuplicates: true // Ignore duplicate records
});

After the first execution of bulkCreate() and the database empty, the value of results:

[
  Test {
    dataValues: {
      value: 'a',
      createdAt: 2020-07-12T12:01:08.695Z,
      updatedAt: 2020-07-12T12:01:08.695Z
    },
    _previousDataValues: {
      value: 'a',
      createdAt: 2020-07-12T12:01:08.695Z,
      updatedAt: 2020-07-12T12:01:08.695Z
    },
    _changed: Set {},
    _options: {
      isNewRecord: true,
      _schema: null,
      _schemaDelimiter: '',
      include: undefined
    },
    isNewRecord: false
  },
  Test {
    dataValues: {
      value: 'b',
      createdAt: 2020-07-12T12:01:08.695Z,
      updatedAt: 2020-07-12T12:01:08.695Z
    },
    _previousDataValues: {
      value: 'b',
      createdAt: 2020-07-12T12:01:08.695Z,
      updatedAt: 2020-07-12T12:01:08.695Z
    },
    _changed: Set {},
    _options: {
      isNewRecord: true,
      _schema: null,
      _schemaDelimiter: '',
      include: undefined
    },
    isNewRecord: false
  }
]

I expected true for all isNewRecord in the first execution. What am I missing?

Environment

  • Windows 10 Pro
  • NodeJS v12.16.2
  • sequelize: 6.3.3
  • sqlite3: 5.0.0

Sequelize docs

isNewRecord of Model:

enter image description here

ignoreDuplicates of bulkCreate():

enter image description here

2 Answers

The isNewRecord field is true if the Model instance does not exist in the database.

const user = new User({ ...userData });
console.log(user.isNewRecord); // true
await user.save();
console.log(user.isNewRecord); // false

You need to access _options.isNewRecord.

As this issue states that the isNewRecord only be set to true if the instance has not yet been persisted to the database.

In your case, because you have saved the instance (the first time or second time, it doesn't matter, you already save it) so isNewRecord is set to false.

So as I mention above, if you want to check if your instance is just saved the first time or not, access _options.isNewRecord.

Related