基本上,我有一个MEAN堆栈应用程序,我想在其中定义一个数组大小不同的模式。有人告诉我这是可能的。
我已经成功地在MongoDB上保存了一个JSON对象,它看起来像这样;
{
"Diseases":[
{
"DiseaseName": "Diabetes",
"Severity": "3"
},
{
"DiseaseName": "Psoriasis",
"Severity": "4"
}
],
"Prescriptions": [
{
"Name" : "Insulin",
"Unit" : "100 microgram"
},
{
"Name" : "Cortisone",
"Unit" : "150 microgram"
}
]
}
基本上,我想定义一个模式,其中疾病和处方中的数组元素(对象(的数量可以是任意的。若我理解正确的话,"病"one_answers"方"是一个数组,它包含一个对象中的对象。
以下是您可以使用的示例架构:
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.Schema({
Diseases: [
{
DiseaseName: String,
Severity: Number,
},
],
Prescriptions: [
{
Name: String,
Unit: String,
},
],
});