0

请注意,这不是 this、this、this 的副本,因为需要不是对另一个集合中的文档的引用,而是对集合本身的引用

我正在使用mongoose-schema-extend为内容创建层次结构。

假设我有这个:

/**
 * Base class for content
 */
var ContentSchema = new Schema({
  URI: {type: String, trim: true, unique: true, required: true },
  auth: {type: [Schema.Types.ObjectId], ref: 'User'},
  timestamps: {
    creation: {type: Date, default: Date.now},
    lastModified: {type: Date, default: Date.now}
  }
}, {collection: 'content'}); // The plural form of content is content


/**
 * Pages are a content containing a body and a title
 */
var PageSchema = ContentSchema.extend({
  title: {type: String, trim: true, unique: true, required: true },
  format: {type: String, trim: true, required: true, validate: /^(md|html)$/, default: 'html' },
  body: {type: String, trim: true, required: true}
});

/**
 * Articles are pages with a reference to its author and a list of tags
 * articles may have a summary
 */
var ArticleSchema = PageSchema.extend({
  author: { type: Schema.Types.ObjectId, ref: 'User', required: true },
  summary: { type: String },
  tags: { type: [String] }
});

现在,我想创建另一个模式,它是内容的子类型,但代表一组内容,如下所示:

/**
 * Content sets are groups of content intended to be displayed by views
 */
var ContentSetSchema = ContentSchema.extend({
  name: {type: String, trim: true, unique: true, required: true },
  description: {type: String },
  content: [{
      source: { type: [OTHER_SCHEMA] }, // <- HERE
      filter: {type: String, trim: true },
      order: {type: String, trim: true }
  }]
})

因此,content此模式的属性应该是对任何其他模式的引用。

可能吗?

4

1 回答 1

0

我想出的最好的方法是使用字符串、鉴别器键和验证器:

var ContentSchema = new Schema({
// ...
}, {collection: 'content', discriminatorKey : '_type'});

var ContentSetSchema = ContentSchema.extend({
  // ...
  content: [{
    source: { type: [String], validate: doesItExist }
  }]
});

function doesItExist(type, result) {
  ContentModel.distinct('_type').exec()
  .then((contentTypes) =>
    respond(contentTypes.some((validType) => validType === type)));
}

但是有了这个解决方案(此时已经足够好了),我只能为已经在数据库中注册的内容类型创建 ContentSets。

于 2015-11-06T11:37:49.067 回答