首页 > 解决方案 > MongoDB/Mongoose:对同一集合中不同类型的文档使用不同的方案

问题描述

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

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

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

“图像”帖子可能是:

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

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

谢谢!

标签: databasemongodbmongoosedatabase-designmongoose-schema

解决方案


您可以将它们合二为一,

你的模型:

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);

推荐阅读