node.js - Mongoose 模式 - 具有共享属性的嵌套对象
问题描述
我是 MongoDB 和 Mongoose 的新手,并试图找出处理创建模式的最佳方法。我更习惯于关系数据库,但我希望这将适用于 Mongo。
我正在创建“扩展”其他对象的对象。例如,我有一个人对象,我想将其用作父对象或祖父对象的起点。父母和祖父母都可能具有超出基本人所具有的附加值(我只是在每个中包含一个示例)...
const personSchema = new mongoose.Schema({
name: String,
birthDate: Date,
deathDate: Date,
});
const parentSchema = new mongoose.Schema({
//all the stuff a person has + below:
children: [personSchemas?] //[array of persons, important... parents can also be children,
multiple parents will share the same child]
parentingStyle: String,
})
const grandParentSchema = new mongoose.Schema({
// stuff that a parent has plus
grandparentingStyle: String,
})
解决方案
我认为以下帖子包含一些可能对您有所帮助的答案: Referencing another schema in Mongoose
除此之外,我还建议您将父母和祖父母定义为角色,也许是这样:
var mongoose = require('mongoose');
const PersonSchema = new mongoose.Schema({
person_id: {
type: mongoose.Schema.Types.ObjectId
},
name: String,
birthDate: Date,
deathDate: Date,
//the following is if you want later to fetch persons by role
role: {
type: string,
enum: ["parent", "grandParent","child"],
}
});
//Then you could do it this way
const ParentSchema = new mongoose.Schema({
//all the stuff a person has + below:
children: [personSchemas],
parentingStyle: String
})
//Or this way
const ParentSchema = new mongoose.Schema({
//all the stuff a person has + below:
children: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Person'
}
parentingStyle: String,
})
const GrandParentSchema = new mongoose.Schema({
// same as for parents (ether way)
// stuff that a parent has plus
grandparentingStyle: String
})
在非关系数据库中,这实际上取决于您以后想对数据做什么。“关节”(与关系数据库比较)更容易创建,可以通过引用 id 或获取整个数组(就像您所做的那样),或者只需稍后进行更复杂的查询。
推荐阅读
- windows - Windows 中的 Meteor 服务器日志在哪里?
- kubernetes - 为内存达到 90% 且未暴露于 Internet(后端微服务)的 kubernetes pod 配置通知/警报的方法
- sql-server - 检索过程可选参数列表的 SQL 语句
- r - R Shiny:减少过滤数据帧的重复代码
- sql-server - 如何在 SQL Server 中导入大型 CSV 文件
- python - 删除 django 搜索中的重复结果
- asp.net-mvc-routing - 为什么 Blazor SPA 中的路由消息不明确?
- java - 配置警告中不存在此类片段
- python - 在 PySpark 中为镶木地板文件过滤日期时间范围和时区
- java - 颠簸转换 JSON 规范