1

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 ?

2
  • Do you use mongoose? Commented May 26, 2017 at 8:49
  • no, I only use the mongodb driver Commented May 26, 2017 at 8:59

1 Answer 1

1

In mongoose these things are done easily. But as far as you don't, I can suggest you such flow:

  • you have collection base in mongo, with field type, that specifies foo or bar instance
  • implement deserialize method in base
  • you implement serialize method in each child class
  • you use your methods, when having array of base objects

I would modify base class:

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

  serialize(model) {
    throw new Error('not implemented')
  }

  deserialize(mongoModel) {
    // very rude, just to catch the point
    // most probably, you'll have to map object before creating new instance
    if (mongoModel.type === 'Foo') return new Foo(mongoModel);
    else return new Bar(mongoModel);
  }
}

I'll write approximate implementation of these methods:

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

  serialize(model) {
    // again very rude, it dependes on your logic
    return JSON.stringify(model);
  }
}

And then, assuming you have array of Base objects you can easily map them:

const mongoBaseModels = baseObjects.map(el => el.serialize(el))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.