【问题标题】:MongoDB/Mongoose: using different schemes for different types of document in the same collectionMongoDB/Mongoose:对同一集合中不同类型的文档使用不同的方案
【发布时间】:2021-07-13 12:53:31
【问题描述】:

假设我在“帖子”集合中有文档。我想将这些文档视为一个集合 - 例如,搜索它们或对所有文档一起运行 db.posts.find()。

但是,有明显不同的帖子类型,理想情况下应该有不同的架构。例如,“文本”帖子可能是:

post_type: "text",
author: String,
title: String,
body: String

“图片”帖子可能是:

post_type: "image",
uri: String,
thumbnail: String

是否有一种简洁的方法可以为同一集合中的不同类型文档定义多个模式?

谢谢!

【问题讨论】:

    标签: database mongodb mongoose database-design mongoose-schema


    【解决方案1】:

    您可以将它们合二为一,

    你的模型:

    post_type: "text",
    author: String,
    title: String,
    body: String,
    uri: String,
    thumbnail: String
    

    保存时只需使用需要的字段。

    1. 另存为类型:文本
    const body = {
     post_type: "text",
     author: String,
     title: String,
     body: String
    }
    
    your_model.save(body);
    
    1. 另存为类型:图片
    const body = {
     post_type: "image",
     uri: String,
     thumbnail: String
    }
    
    your_model.save(body);
    

    【讨论】:

    • 感谢您的回复 - 这种方法感觉就像它造成了一个非常混乱的架构。我给出的例子被简化了——实际上我会有几种“类型”的文档,每个都有几十个独特的字段。如果有一个很好的方法来处理这个问题,我很感兴趣。
    • 更好地用于不同的架构
    • 我将如何实现我想要的,即同时在所有这些不同模式上的 find() ?我想我可以设置我自己的辅助函数,在多个模式上运行 Promise.all() 和 find(),但是我将无法使用 MongoDB 功能,如 limit()
    • 那你必须尝试我告诉你的那个,它只会让你的模型文件变得凌乱,但你可以更容易地实现你的其他功能。
    • @dan674 你也可以试试这个方法Mongoose : SubDocuments
    猜你喜欢
    • 2012-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-02
    • 2021-04-01
    • 2015-06-13
    • 1970-01-01
    • 2014-02-21
    相关资源
    最近更新 更多