【问题标题】:Mongoose schema - nested objects with shared propertiesMongoose 模式 - 具有共享属性的嵌套对象
【发布时间】:2021-05-24 02:00:16
【问题描述】:

我是 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.js mongodb mongoose mongoose-schema


    【解决方案1】:

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

    【讨论】:

    • 感谢您的回答。在您的建议中,我看到子数据如何传递给子数组中的父级,但是我如何保留该特定父级的人员属性,或者我手动定义它们。有点认为我的父母继承了人
    • 嗯,我不确定我是否在这里得到了你的问题,所以如果你能更准确一点,我将不胜感激,但它是一种继承。我认为您甚至可以从每个父母的人中收集特定的孩子。我建议您在做任何事情之前先阅读有关 MongoDB 的更多信息,因为您似乎仍然以关系数据库的方式思考。请看这篇帖子stackoverflow.com/questions/5373198/…
    猜你喜欢
    • 1970-01-01
    • 2018-12-22
    • 1970-01-01
    • 2019-12-21
    • 1970-01-01
    • 2017-01-25
    • 1970-01-01
    • 2018-11-14
    • 1970-01-01
    相关资源
    最近更新 更多