2015-11-06 20 views
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屬性應該是對任何其他模式的引用。

可能嗎?

回答

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已經在數據庫中註冊過的內容。