在mongoose中为对象数组设置默认值

3
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var patientSchema = new Schema({
    resourceType : {type :String, default : 'Patient' },
    id : {type : String, default : 'example'},
    text : [{
        status : {type : String, default : 'generated'},
        div :{type : String, default :'<div> Something </div>'}
    }],
    active : {type : String, default : 'true'},
    identifier : [{
        use : {type : String, default : 'official'},
        system : {type : String, default : 'urn:oid:1.2.36.146.595.217.0.1'},
        assinger :[{
            display : {type : String, default : 'Acme Healthcare'},
        }]

    }],
    name: [{
        use : {type : String, default : 'official'},
        first_name : {type : String, default : ''},
        second_name : {type : String, default : ''}
    }],
    gender :{type : String,  default : ''},
    birthDate :{type : String,  default : ''},
    telecom : [{
        system : {type : String, default : ''},
        value : {type : String, default : ''}
    }],
    address : [{
        use : {type : String, default : 'official'},
        text : {type : String, default : ''},
        city : {type : String, default : ''},
        district : {type : String, default : ''},
        state : {type : String, default : ''},
        postalcode :{type : String, default : ''}
    }]
});

var patients = mongoose.model('Patients',patientSchema);
module.exports = patients;

这是我的模型类,我通过 post-man 工具发送值, 默认值在字段数组中,例如。
text : [{
        status : {type : String, default : 'generated'},
        div :{type : String, default :'<div> Something </div>'}
    }],

状态和div未存储默认值。
我需要将状态和div的值作为默认值存储!
2个回答

7
您可以使用子方案或文档代替!
var patientTextSchema = new Schema({ 
   status : {type : String, default : 'generated'},
   div :{type : String, default :'<div> Something </div>'} 
});

... ommited for clarity
var patientSchema = new Schema({
  text: [patientTextSchema]
})

这样,您可以使用patient.text.push({})添加默认的patientTextSchema,或使用patient.text.push({status:“another_status”})添加(部分)填写的模式。
来源:http://mongoosejs.com/docs/subdocs.html

所以您希望我将文本字段作为架构,然后将其推入文本字段中(询问以确保我已经理解了答案)。 - Grijan
1
是的,你理解得很正确,这看起来需要更多的工作,但同时它也是可重用的,这样当你想在其他地方添加一个文本字段的时候,就能省下时间! - Brord van Wierst

2
您可以使用以下方法在mongoose中创建具有默认值的对象数组:
const organisationSchema = new mongoose.Schema({
        name: {
            type: String,
            required: true
        },
        brands: {
            type: [
                {
                    type: mongoose.Schema.Types.ObjectId,
                    ref: 'brand'
                }
            ],
            default: []
        },
        users: {
            type: [
                {
                    type: mongoose.Schema.Types.ObjectId,
                    ref: 'user'
                }
            ],
            default: []
        }
    }, { timestamps: true });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接