【问题标题】:Schema for a JSON object with varying index size具有不同索引大小的 JSON 对象的架构
【发布时间】:2020-11-10 01:12:37
【问题描述】:

基本上,我有一个 MEAN 堆栈应用程序,我想在其中定义数组大小变化的模式。有人告诉我这是可能的。

我已成功在 MongoDB 上保存了一个 JSON 对象,如下所示;

{
    "Diseases":[
                {
                "DiseaseName": "Diabetes",
                "Severity": "3"
                
            },
                {
                "DiseaseName": "Psoriasis",
                "Severity": "4"
            }
        ],
    
  "Prescriptions": [
            {
                "Name" : "Insulin",
                "Unit" : "100 microgram"
            },
          {
            "Name" : "Cortisone",
            "Unit" : "150 microgram"
          }        
    ]       
}

基本上,我想定义一个模式,其中疾病和处方中的数组元素(对象)的数量可以是任意的。如果我理解正确的话,Diseases 和 Prescriptions 是一个数组,其中包含包含在一个对象中的对象。

【问题讨论】:

  • 无法得到您的问题,您能澄清一下吗?你说的随意是什么意思?它应该是某个常数吗?或无限。如果你不想限制数组的大小,它是由猫鼬设置的,所以你不必担心。请在提出问题时更加具体,并且请务必先阅读堆栈文档,
  • 任意的意思是没有设定的号码,随便什么都可以。例如,患者可能患有任何(或根本没有疾病!)多种疾病,与处方类似。我不知道如何在后端为此编写架构(通常在 Patient.model.js 中)

标签: mongodb mongoose backend mean-stack mongoose-schema


【解决方案1】:

这是您可以使用的示例架构:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const diseaseSchema = new Schema({
    diseaseName:{               
        type: String,
        required: true,
    },
    severity: {
        type: Number,
        min:0,
        max: 5,
        required: true
    }
},{
    timestamps: true
});

const prescriptionSchema = new Schema({
    name:{               
        type: String,
        required: true,
    },
    unit: {
        type: String,
        required: true
    }
},{
    timestamps: true
});


const patientSchema = new Schema({
    diseases: [diseaseSchema]
    prescriptions: [prescriptionSchema]
},{
    timestamps: true
});

var Patients = mongoose.model('Patient', patientSchema);

module.exports = Patients;

参考mongoose docs

【讨论】:

    【解决方案2】:

    从您的问题来看,您似乎需要数据库中对象数组的架构。这是你可以做到的。

     mongoose.Schema({
          Diseases: [
            {
              DiseaseName: String,
              Severity: Number,
            },
          ],
          Prescriptions: [
            {
              Name: String,
              Unit: String,
            },
          ],
        });
    

    【讨论】:

      猜你喜欢
      • 2021-08-19
      • 1970-01-01
      • 1970-01-01
      • 2020-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-16
      相关资源
      最近更新 更多