Validation/Conversion for JSON Type
See original GitHub issueHi! I’ve been using Sequelize for a bit now, and I’m incredibly impressed. Extremely easy to use!
I’m migrating from MongoDB (via Mongoose) to PostgreSQL. One of the big features I miss is being able to store encapsulated objects inline as subdocuments. For example:
{
itemName: "foo",
properties: {
height: 5.3
},
parts: [{
name: "bar",
description: "bars the foo"
}, {
name: "baz",
description: "bazs the foo"
}]
}
I know I can put these subobjects in separate tables and hook them up using associations. However, for truly encapsulated objects this adds a lot of overhead and complexity.
Alternatively, since this is PostgreSQL, I can use the JSON/JSONB type and store these inline. That works great, but I lose the awesome validation and type conversion I get with standard fields. In Mongoose, you could define the schema above like:
{
itemName: String,
properties: {
height: Number
},
parts: [{
name: String,
description: String
}]
}
Mongoose would take care of validating the subobjects (most of the time). It doesn’t seem that Sequelize has support for this out of the box. However, I was wondering if there was a way I could manually use the validation and type conversion built-in to Sequelize using hooks, setters, or custom validation. I’m just not sure how to call these outside of the normal model definition.
For example, how could I convert the property height to a float if it is set as a string? I could check this in a setter, but how can I use Sequelize’s type conversion for this?
And how could I validate that height is greater than 0? I could write a custom validation for the field and check that the value is greater than 0, but it would be nice to use the built-in validators like “min”.
Any suggestions?
Issue Analytics
- State:
- Created 8 years ago
- Reactions:3
- Comments:18 (3 by maintainers)
Well, here’s hoping this gets implemented at some point. It’s really nifty for encapsulation. I ended up doing the schema validation with revalidator. It’s not as pretty or simple as the Mongoose or Sequelize declarations, but it does the trick. Here’s what my example above ends up looking like:
Does anyone work on this feature? I can try to implement it.