请注意,这不是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 :(得分: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。