Ale*_*uck 0 schema mongoose mongodb
如果我有一个 model 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())
};
Run Code Online (Sandbox Code Playgroud)
现在,在Post架构中,应该有一系列具有不同类型的附件:
var Attachment = require('./attachment');
var PostSchema = new Schema(
text:{type: String},
attachments: [Material] // Could be Material.Link, Material.YoutubeVideo, etc
});
Run Code Online (Sandbox Code Playgroud)
当我这样做时,我收到一条错误消息“未定义类型Model。GoogleDriveFile您尝试过嵌套架构吗?您只能使用引用或数组进行嵌套。”
我不知道这个错误意味着什么,也找不到任何解释如何执行此操作的文档。帮助?
小智 6
尝试执行以下操作:
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({}))
};
Run Code Online (Sandbox Code Playgroud)
关键是不要使用猫鼬模型,使用父文档模式的 schema.path 作为鉴别器的基础。
在此链接上搜索术语docArray:Mongoose Discriminator 文档