Other commenters have observed OP might have been playing with a primary key, which has special behaviour around validation. But the title asks about 'values' generally. The common advice on that question is:
- Remove the
allowNull requirement on the model definition, or
- Use a hook to manually insert the default.
These are not great answers. Option 1 is effectively permanently distorting your model (and validations). Option 2 is closer to correct, but still annoying and unintuitive: what's the point in setting a default if I have to build logic to apply it?
For the record: if you did want to go with Option 2, beforeCreate will not help (as you have noticed) because that hook is called after validation. You would have to use the beforeValidate hook-- and then specifically add logic to ensure the hook is only triggered upon the record creation. Like so:
hooks: {
beforeValidate: async (user) => {
if (user.isNewRecord) await applyDefaults(user);
},
}
This^ works. But here's the real solution:
Don't write any hooks. Define your default value on the model like so:
const userSchema = db.define('USER', {
id: {
type: Sequelize.UUIDV4,
allowNull: false,
primaryKey: true,
defaultValue: generateNewUUID()
}})
Then, when creating instances, use Model.build() instead of Model.create(). The former applies the defaults properly, before validation. Eg:
var user = User.build({
email: "[email protected]"
})
user = await user.save()
console.log(user.id) // <--- Now works as expected
CAVEAT: At time of writing, Sequelize still doesn't seem to support promises for default values. If you need to apply a resolved promise as defaultValue, you're stuck with Options 1 or 2.
id, as it will always be generated from backend side, so what's the meaning of validation?allowNull: false