首页 > 解决方案 > 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,
})

标签: node.jsmongodbmongoosemongoose-schema

解决方案


我认为以下帖子包含一些可能对您有所帮助的答案: 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 或获取整个数组(就像您所做的那样),或者只需稍后进行更复杂的查询。


推荐阅读