Woodshop
Search…
Make a field readOnly with Sequelize
Sequelize does not allow by itself to define a field as readOnly. But you can do so by using on of Sequelize's addons named sequelize-noupdate-attributes.
the LastName field is readOnly in Sequelize but not the email field

Requirements

How it works

Directory: /models

This directory contains the files where your models are defined with Sequelize. To make fields readOnly you need to require the sequelize-noupdate-attributes package and add the noUpdate option to the relevant fields.
The noUpdate option will throw an error if the user tries to update a field that already has a value. However the user will be able to update a field that has a null value.
models/users.js
1
const sequelizeNoUpdateAttributes = require('sequelize-noupdate-attributes');
2
3
module.exports = (sequelize, DataTypes) => {
4
const { Sequelize } = sequelize;
5
sequelizeNoUpdateAttributes(sequelize);
6
7
const Users = sequelize.define('users', {
8
firstName: {
9
type: DataTypes.STRING,
10
noUpdate: true,
11
},
12
lastName: {
13
type: DataTypes.STRING,
14
noUpdate: true,
15
},
16
email: {
17
type: DataTypes.STRING,
18
},
19
}, {
20
tableName: 'users',
21
underscored: true,
22
timestamps: false,
23
schema: process.env.DATABASE_SCHEMA,
24
});
25
26
return Users;
27
};
28
Copied!
Last modified 1yr ago