如何为mongoose子文档指定架构属性?

时间:2016-08-19 23:12:32

标签: node.js mongodb mongoose mongoose-schema

我正在构建一个插件,需要为其中一个子文档集合字段指定属性。有人提到Array.newInstance 正式执行此操作的方式。

所以,而不是......

statics

......就是这个......

var familySchema = mongoose.Schema({
    surName   : { type: String },
    members   : { type: [ personSchema ], minLength: 1, maxLength: 10 } 
});

我发现没有var familySchema = mongoose.Schema({ surName : { type: String }, members : [ personSchema ] }); familySchema.static('minLength', 1); familySchema.static('maxLength', 10); minLength。该插件将处理此问题。

我一直在查看文档,无法找到任何提及官方方式的内容。一个与另一个有益吗?

1 个答案:

答案 0 :(得分:0)

你是对的,对于ref数组没有minLength这样的东西。您必须使用自定义验证

var validateFamilyLength = function (members) {
    return members.length > 1 && members.length < 10;
};

var familySchema = mongoose.Schema({
    surName   : { type: String },
    members   : { 
        type: [personSchema], 
        validate: [validateFamilyLength, 'Not valid members count']
    } 
});

但我强烈建议改用refs

var familySchema = mongoose.Schema({
    surName   : { type: String },
    members   : [{
        type: mongoose.Schema.ObjectId,
        ref: 'Person',
        validate: [validateFamilyLength, 'Not valid members count']
    }]
});