masumsoft / express-cassandra

Cassandra ORM/ODM/OGM for NodeJS with support for Apache Cassandra, ScyllaDB, Datastax Enterprise, Elassandra & JanusGraph.
http://express-cassandra.readthedocs.io
GNU Lesser General Public License v3.0
232 stars 68 forks source link

Virtual fields not set on initial instance creation #151

Closed measwel closed 6 years ago

measwel commented 6 years ago

When a new entity is created based on an object which holds data:

new models.instance['User'](data)

Virtual fields defined for this entity are not set. In my case email_encrypted is not set, even if email is present in the data object.

    email: {
      "type": "text",
      "virtual": {
        get: function () {
          if (this.email_encrypted) {
            return crypto.decryptWithKey(this.email_encrypted, config.private_key);
          } else {
            return;
          }
        },
        set: function (email) {
          this.email_encrypted = crypto.encryptWithKey(email, config.private_key);
        }
      }
    },
masumsoft commented 6 years ago

Does the model schema contain the email_encrypted field? I guess you should define the email_encrypted field with type text to make it work.

measwel commented 6 years ago

Yes, the model has it:

    email_encrypted: {
      type: "text"
    },

It does not get set.

measwel commented 6 years ago

As a consequence, I am also not able to update models directly by the update or save function. As a workaround, I first read the entity from the db, then copy the modified fields from the transfer ( data ) object with this function:

module.exports.modifyUpsertEntity = function (entity_transfer, entity_upsert) {
  for (var property in entity_transfer) {
    if (!entity_transfer.hasOwnProperty(property)) {
      continue;
    } else {
      // console.log("COPY: ", property, entity_upsert[property], entity_transfer[property]);
      if (entity_upsert.hasOwnProperty(property)) {
        entity_upsert[property] = entity_transfer[property];
      }
    }
  }
  return entity_upsert;
};

Entity_upsert is the entity I read from the db, entity_transfer holds the fields that are to be modified. After this function returns, I execute .save on it.

masumsoft commented 6 years ago

Fixed in v2.2.2