Thursday | 21 NOV 2024
[ previous ]
[ next ]

Using UUID as a Primary Key

Title:
Date: 2022-11-17
Tags:  

I really like using a UUID as a primary key as it hides the information of when a user joins a service. Something about knowing that bothers me.

So I had actually undertaken a bit of a painful migration in the past to get off sequential ids and I've now begun to use the UUID feature in sequelize which makes it extremely easy to use UUIDs as a primary key.

Here is a very simple example of getting started with using UUID with sequelize and sqlite3.

const { Sequelize, Model, DataTypes } = require('sequelize');

const sequelize = new Sequelize({
    dialect: 'sqlite',
    storage: 'db/mydb.db'
});

const db = { };

db.Sequelize = Sequelize;
db.sequelize = sequelize;

db.User = sequelize.define('User', {
    id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
    },
    username: DataTypes.STRING,
    password: DataTypes.STRING,
    admin: DataTypes.BOOLEAN,
});

module.exports = db;