如果我有一个模型Attachment
,可以分为4种类型:Link
,YoutubeVideo
,GoogleDriveFile
和GoogleDriveFolder
,我该怎么办?使用Mongoose将Attachment
区分为这些类型,并允许它们成为另一个模式中的子文档; Post
?
我已经创建了基本Attachment
模型,并使用鉴别器将其划分为单独的模型:
var AttachmentSchema = new Schema({
id: {type: String, required: true},
title: {type: String, required: true}
});
var Attachment = mongoose.model('Material', AttachmentSchema);
module.exports = {
DriveFile: Attachment.discriminator('GoogleDriveFile', new mongoose.Schema()),
DriveFolder: Attachment.discriminator('GoogleDriveFolder', new mongoose.Schema()),
Link: Attachment.discriminator('Link', new mongoose.Schema()),
YoutubeVideo: Attachment.discriminator('YoutubeVideo', new mongoose.Schema())
};
现在,在Post
架构中,应该有一系列附件,具有不同的类型:
var Attachment = require('./attachment');
var PostSchema = new Schema(
text:{type: String},
attachments: [Material] // Could be Material.Link, Material.YoutubeVideo, etc
});
当我这样做时,我在Model
收到错误说"未定义类型GoogleDriveFile
。你尝试过嵌套Schemas吗?您只能使用refs或数组进行嵌套。"
我不知道这个错误意味着什么,我找不到任何解释如何执行此操作的文档。帮助
答案 0 :(得分:3)
尝试执行以下操作:
var AttachmentSchema = new Schema({
id: {type: String, required: true},
title: {type: String, required: true}
});
var PostSchema = new Schema({
text: { type: String },
attachments: [ AttachmentSchema ] // Could be Material.Link, Material.YoutubeVideo, etc
});
var attachmentArray = PostSchema.path('attachments');
module.exports = {
Post: mongoose.model('Post', PostSchema),
DriveFile: attachmentArray.discriminator('GoogleDriveFile', new mongoose.Schema({})),
DriveFolder: attachmentArray.discriminator('GoogleDriveFolder', new mongoose.Schema({})),
Link: attachmentArray.discriminator('Link', new mongoose.Schema({})),
YoutubeVideo: attachmentArray.discriminator('YoutubeVideo', new mongoose.Schema({}))
};
关键是不要使用mongoose模型使用父文档模式的schema.path作为鉴别器的基础。
在此链接上搜索 docArray 一词:Mongoose Discriminator documentation