【问题标题】:Mongoose - Divide subdocuments using discriminatorsMongoose - 使用鉴别器划分子文档
【发布时间】:2017-08-16 19:52:38
【问题描述】:

如果我有一个模型Attachment,可以分为4种类型:LinkYoutubeVideoGoogleDriveFileGoogleDriveFolder,如何使用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
});

执行此操作时,我收到一条错误消息,提示“GoogleDriveFile 处的未定义类型 Model。您是否尝试嵌套架构?您只能使用引用或数组进行嵌套。”

我不知道这个错误是什么意思,也找不到任何解释如何执行此操作的文档。帮忙?

【问题讨论】:

标签: mongodb mongoose schema


【解决方案1】:

尝试执行以下操作:

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

关键是不要使用猫鼬模型,使用父文档模式的 schema.path 作为鉴别器的基础。

在此链接上搜索术语 docArrayMongoose Discriminator documentation

【讨论】:

  • 谢谢先生,您拯救了这一天。
  • 你好。我正在使用 Typescript 和 Mongoose,而鉴别器方法似乎在 Schema 类型上不存在。我在这里错过了什么吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-15
  • 2017-02-12
  • 2013-03-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多