Objection.js: Option to ignore additional properties

Created on 24 Nov 2017  路  7Comments  路  Source: Vincit/objection.js

Currently it is only possible either to silently include additional (undefined in schema) properties or to throw exception when these are found. It is not currently possible to silently omit fields that are not in the schema during .fromJson instantiation. I presume this could be a new flag in ModelOptions entity that is passed to .fromJson method or an explicit argument for .fromJson method.

I could provide a PR for this functionality if this change is approved.

Most helpful comment

I think this is easy enough to implement in userland and it shouldn't be added to core:

const { Model, lodash } = require('objection');


class BaseModel extends Model {
  $parseJson(json, opt) {
    const json = super.$parseJson(json, opt);
    return lodash.pick(json, Object.keys(this.constructor.jsonSchema.properties));
  }
}

Also there is this if it's enought to remove the properties before they get to the database.

All 7 comments

@koskimas Could you please comment whether you think that this is an appropriate change? I obviously can implement this change on our consumer part, but my preferred option is to contribute to upstream when it makes sense to.

I think this is easy enough to implement in userland and it shouldn't be added to core:

const { Model, lodash } = require('objection');


class BaseModel extends Model {
  $parseJson(json, opt) {
    const json = super.$parseJson(json, opt);
    return lodash.pick(json, Object.keys(this.constructor.jsonSchema.properties));
  }
}

Also there is this if it's enought to remove the properties before they get to the database.

This ajv option can also be handy: removeAdditional

@kapouer @koskimas Thank you for the extremely useful information! Is there any value in me creating new Recipe PR for the objection.js documentation?

@igor-savin-ht I think a recipe could be useful. The difficult part is to use the correct words so that people find that recipe. I don't think many people find pickJsonSchemaProperties because of its name.

Correct me if i'm wrong, but isn't pickJsonSchemaProperties only working on top-level properties ?
If i remember well, it's the reason i ended up using removeAdditional.

@kapouer That's correct. Its purpose is to remove nonexistent __columns__ from being inserted to database. Nested json objects are unaffected. It works for nested relations though (if they have the flag on).

Was this page helpful?
0 / 5 - 0 ratings

Related issues

haywirez picture haywirez  路  3Comments

mycahjay-nms picture mycahjay-nms  路  4Comments

nicolaracco picture nicolaracco  路  3Comments

rickmed picture rickmed  路  4Comments

apronin83 picture apronin83  路  3Comments