0

必要なのは別のコレクションからのドキュメントへの参照ではなく、コレクション自体への参照であるため、これはthis 、 thisthisの複製ではないことに注意してください。

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

しかし、このソリューション (現時点では十分です) を使用すると、既にデータベースに登録されている種類のコンテンツに対してのみ ContentSet を作成できます。

于 2015-11-06T11:37:49.067 に答える