0

我想在 NoSQL / Document DB 中实现多态对象?什么是最佳实践?

示例:大师级 项目对象(都应该有 Item.Title、Item.Subtitle、Item.IconURL)

子类:ItemPhoto、ItemPDF、ItemURL、ItemHTML (每个子类都有不同的属性)

我想一般地列出所有项目 - 然后在我向下钻取时获取特定数据。

可能的选项:

保存两个不同的文档 - 带有主/子类型和 ID 将所有文档保存为带有内部项目对象的子类文档

其他选择??

谢谢

4

1 回答 1

1

CouchDB stores documents (data), not classes (data with code). There's the code in map, validation, list, and show functions which handle documents, but those documents are plain objects that carry data only.

In your example, you can define a library function to check that a given document contains the data of an item, and then use this function to decide what to do. For example:

// in a "appTypes" library:
exports.isItem = function(doc) {
  return doc.Title && doc.Subtitle && doc.IconURL;
}

// in a map function
function(doc) {
  var appTypes = require('appTypes');
  if (appTypes.isItem(doc)) {
    // doc is an Item...
  }
}

Obviously you can put all code belonging to an Item in an Item class and create instances of that class initialized with the data in the doc. But that's your choice, and does not change how CouchDB will handle the document.

于 2012-08-24T13:46:09.953 回答