如何避免MONGODB模型中的模式重复

时间:2019-01-09 09:39:23

标签: node.js mongodb mongoose mongoose-schema

考虑下面提到的document

const testSchema = new mongoose.Schema({
    test1: {
        name: String,
        email: String
    },
    test2: {
        name: String,
        email: String
    }
    test3: {
        name: String,
        email: String
    }
    test4: {
        name: String,
        email: String
    }
});

在上述模型test1, test2, test3...中,重复数据已存在。有办法避免这种方法吗?

1 个答案:

答案 0 :(得分:1)

假设您的架构保留了可以存储的记录列表,例如

const RecordsSchema = new mongoose.Schema({
    name: {              //
        type: String,    //
        required: true,  //     dummy
        maxLength: 254   //              
    },                   //
    tests: {
        type: [mongoose.Schema.ObjectId],
        ref: 'TestSchema',
        required: false
    }
}

const TestSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        maxLength: 254
    },
    email: {
        type: String,
        required: true,
        maxLength: 254,
        trim: true
    }
}

这样,您将创建一个模型,该模型将独立定义每个测试,然后您的控制器可以将该Test对象链接到RecordsSchema模型中的数组