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

时间:2017-12-20 14:25:02

标签: node.js mongodb mongoose

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>'}
    }],

status和div没有存储默认值

我需要将status和div的值存储为默认值!

2 个答案:

答案 0 :(得分:3)

您可以使用子方案/文档!

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

答案 1 :(得分:1)

您可以使用以下方法以默认的猫鼬创建对象数组:

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 });