database - MongoDB/Mongoose:对同一集合中不同类型的文档使用不同的方案
问题描述
假设我在集合“帖子”中有文档。我想将这些文档视为一个集合 - 例如,搜索它们或对所有文档一起运行 db.posts.find()。
然而,有明显不同类型的帖子,理想情况下应该有不同的模式。例如,“文本”帖子可能是:
post_type: "text",
author: String,
title: String,
body: String
“图像”帖子可能是:
post_type: "image",
uri: String,
thumbnail: String
是否有一种干净的方法可以为同一集合中的不同类型文档定义多个模式?
谢谢!
解决方案
您可以将它们合二为一,
你的模型:
post_type: "text",
author: String,
title: String,
body: String,
uri: String,
thumbnail: String
保存时只需使用所需的字段。
- 另存为类型:文本
const body = {
post_type: "text",
author: String,
title: String,
body: String
}
your_model.save(body);
- 保存为类型:图像
const body = {
post_type: "image",
uri: String,
thumbnail: String
}
your_model.save(body);
推荐阅读
- cypress - 赛普拉斯 - 根据值使用自定义命令
- powershell - VSCode 集成终端默认为 powershell 核心
- php - 在表格列中打印多维数组数据
- angular - 如何在角度 8 中使用 for 循环显示更多/隐藏更少切换以显示更多文本
- angular - 如何在 Angular 7 中管理 API 函数调用服务
- python - Python Flask:我有一个烧瓶中间件,我想在其中计算请求所花费的时间并将其添加到响应的标头中
- javascript - 运行/停止/更改使用弹性豆茎的应用程序
- c# - 如何在运行时使用众所周知的属性查找正在运行的 MSBuild 版本 - .NET Core 或 .NET Framework
- javascript - 请求没有音频/视频捕获的完整 MediaDeviceInfo
- tensorflow - 将代码从 Colab 转移到 Jupyter Notebook