question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Validation/Conversion for JSON Type

See original GitHub issue

Hi! 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:closed
  • Created 8 years ago
  • Reactions:3
  • Comments:18 (3 by maintainers)

github_iconTop GitHub Comments

11reactions
dtjohnsoncommented, May 27, 2015

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:

var revalidator = require('revalidator');

var schemaValidator = function (schema) {
    return function (value) {
        var results = revalidator.validate(value, schema);
        if (!results.valid) throw new Error(JSON.stringify(results.errors));
    };
};

sequelize.define("Item", {
    itemName: DataTypes.STRING,
    properties: {
        type: DataTypes.JSONB,
        validate: {
            schema: schemaValidator({
                type: "object",
                properties: {
                    height: { type: "number", exclusiveMinimum: 0, required: true }
                }
            })
        }
    },
    parts: {
        type: DataTypes.JSONB,
        validate: {
            schema: schemaValidator({
                type: "array",
                items: {
                    type: "object",
                    properties: {
                        name: { type: "string", required: true },
                        description: { type: "string", required: true }
                    }
                }
            })
        }
    }
});
1reaction
bjorxicommented, May 26, 2016

Does anyone work on this feature? I can try to implement it.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Ajv supports JSON Type Definition
JSON Type Definition (JTD) is a new specification for defining JSON structures that is very simple to use, comparing with JSON Schema, ...
Read more >
Validating with JSON Schema
The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the...
Read more >
How to Use JSON Schema to Validate JSON Documents in ...
It shows that the schema defined can be used to validate the JSON instances as expected. Incorrect data types or missing some required...
Read more >
JSON Formatter & Validator
The JSON Formatter & Validator beautifies and debugs JSON data with advanced formatting and validation algorithms.
Read more >
JSON Schema Validator and Converter in Java
However, this is not a problem, you can use JsonLoader to convert JSONObject: JsonNode schema = JsonLoader.fromString(object1.toString()); JsonNode data ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found