Friday, 26 May 2017

node.js serialize/deserialize custom objects to mongodb

I have the following architecture:

class Base {
  constructor(initObj) { /* some init */}
  // some methods
}

class Foo extends Base {
  constructor(initObj) { super(initObj); }
  // some methods
}

class Bar extends Base {
  constructor(initObj) { super(initObj); }
  // some methods
}

How can I serialize/deserialize an Array of Base into mongodb ?

For the moment, I save an attribute type on each object to know if its a Foo or a Bar and my Foo and Bar's constructor looks like that:

constructor(initObj) {
  super(initObj);
  if (initObj.fromMongo) this.restore(initObj)
  else this.initialize(initObj)
  this.type = 'bar'; // or baz according to the object
}

because as you can imagine, the creation from a saved object and from new data is not the same.

Does someone knows a less tricky way to realize these operations ?



via Jérémy Pouyet

No comments:

Post a Comment