具有唯一文档的嵌套数组使我“验证失败”

时间:2019-03-05 05:56:49

标签: node.js mongodb mongoose schema unique

我有一个名为 Teacher 的集合,它基于Schema teacherSchema 构建,该集合又包含一个 asignedSchool 数组,包含基于架构 register 的另一个数组。是三个嵌套数组。
并且 asignedSchool 有一个引用另一个集合的文档,并且具有属性的唯一性。但是,当我将第二个元素插入asignedSchool数组中时,它返回如下错误。

{
"success": false,
"message": "Error",
"errors": {
    "errors": {
        "schools.0.school": {
            "message": "school have to be unique",
            "name": "ValidatorError",
            "properties": {
                "message": "school have to be unique",
                "type": "unique",
                "path": "school",
                "value": "5c7dc4430025562f83be3802"
            },
            "kind": "unique",
            "path": "school",
            "value": "5c7dc4430025562f83be3802"
        }
    },
    "_message": "teacher validation failed",
    "message": "teacher validation failed: schools.0.school: school have to be unique",
    "name": "ValidationError"
}
}

但是我插入的ObjectId(5c7dfe3a2e4f7130d0cbd354)与错误中提到的对象不同,我不明白为什么会收到该错误。

下面,我向您展示模式:

teacherSchema

var teacherSchema = new Schema({
    firstName: {
        type: String,
        required: [true, "Name it's necesary"]
    },
    lastName: {
        type: String,
        required: false
    },
    avatar: {
        type: String,
        required: false
    },
    schools:[asignedSchool]
}, {
    timestamps: true
});

已分配的学校

var asignedSchool = new Schema({
    school: {
        type: Schema.Types.ObjectId,
        required: true,
        unique: true
    },
    history: [register]
}, {
    timestamps: true
});

注册

var register = new Schema({
    account: {
        type: Schema.Types.ObjectId,
        ref: models.ACCOUNT
    },
    status: {
        type: String,
        required: true,
        default: teacherStatus.IN_PROGRESS,
        enum: validStatus
    },
    viewed: {
        type: Boolean,
        required: true,
        default: false
    }
}, {
    timestamps: true
});

0 个答案:

没有答案