Sequelize, why is my custom id not unique

I am creating a custom id(primary key) and set a default value(random string using nanoid library) to it so I don’t need to specify an id when I am creating and inserting data to DB(so works like a normal id) but there is one thing I don’t get it, how come if I don’t use a function and return the generated nanoid, I get a validation error…

'use strict';
const { nanoid } = require('nanoid');

module.exports = (sequelize, DataTypes) => {
	const Article = sequelize.define('Article', {
		rid: {
			type: DataTypes.STRING,
			primaryKey: true,
			allowNull: false,
			unique: true,
            /* First way, if I use this way, it won't give me validation error */
			defaultValue: () => {
				const randomId = nanoid(15);
				return randomId;
			},
            /* Second way, if I use this way, I get validation error */
			defaultValue: nanoid(15),
		},
		title: DataTypes.STRING,
		author: DataTypes.STRING,
		body: DataTypes.TEXT,
	});

	return Article;
};

When I use second way, this is the validation error:

 {
  name: 'SequelizeUniqueConstraintError',
  errors: [
    ValidationErrorItem {
      message: 'rid must be unique',
      type: 'unique violation',
      path: 'rid',
      value: 'PIu0Puhvf2rUxRP',
      origin: 'DB',
      instance: [Article],
      validatorKey: 'not_unique',
      validatorName: null,
      validatorArgs: []
    }
  ],
  fields: [ 'rid' ],
  parent: [Error: SQLITE_CONSTRAINT: UNIQUE constraint failed: Articles.rid] {
    errno: 19,
    code: 'SQLITE_CONSTRAINT',
    sql: 'INSERT INTO `Articles` (`rid`,`title`,`author`,`body`,`createdAt`,`updatedAt`) VALUES ($1,$2,$3,$4,$5,$6);'
  },
  original: [Error: SQLITE_CONSTRAINT: UNIQUE constraint failed: Articles.rid] {
    errno: 19,
    code: 'SQLITE_CONSTRAINT',
    sql: 'INSERT INTO `Articles` (`rid`,`title`,`author`,`body`,`createdAt`,`updatedAt`) VALUES ($1,$2,$3,$4,$5,$6);'
  },
  sql: 'INSERT INTO `Articles` (`rid`,`title`,`author`,`body`,`createdAt`,`updatedAt`) VALUES ($1,$2,$3,$4,$5,$6);'
}

I don’t get it, why? and also is this how you create a custom auto generate id(so it works like normal id, which I don’t need to specify the id when I am creating and inserting data) in sequelize?

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.