【问题标题】:node.js serialize/deserialize custom objects to mongodbnode.js 将自定义对象序列化/反序列化到 mongodb
【发布时间】:2017-05-26 08:30:30
【问题描述】:

我有以下架构:

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
}

如何将Base 的数组序列化/反序列化到 mongodb 中?

目前,我在每个对象上保存一个属性 type 以了解它是 Foo 还是 Bar,并且我的 Foo 和 Bar 的构造函数如下所示:

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

因为您可以想象,从已保存对象和从新数据创建是不一样的。

有人知道实现这些操作的不那么棘手的方法吗?

【问题讨论】:

  • 你用猫鼬吗?
  • 不,我只用mongodb驱动

标签: node.js mongodb serialization ecmascript-6


【解决方案1】:

在猫鼬中,这些事情很容易完成。但如果你不这样做,我可以建议你这样的流程:

  • 您在 mongo 中有集合库,具有字段类型,指定 foo 或 bar 实例
  • 在 base 中实现反序列化方法
  • 您在每个子类中实现序列化方法
  • 当有基础对象数组时,你可以使用你的方法

我会修改基类:

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);
  }
}

我会写出这些方法的大致实现:

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

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

然后,假设您有一组 Base 对象,您可以轻松地映射它们:

const mongoBaseModels = baseObjects.map(el => el.serialize(el))

【讨论】:

    猜你喜欢
    • 2019-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多