Node.js Mongodb验证架构数组上的值

时间:2018-10-15 13:34:11

标签: node.js mongodb

我想知道如何验证模式中值是否位于其他值的数组中。看这个例子:

const progressSchema = mongoose.Schema({
    possible_statuses: {
        type: Array
    },
    first_status: {
        type: String
    }
});

这样的POST(插入)示例为:

{
    possible_statuses: ['Untouched', 'In Progress', 'Complete'],
    first_status: 'Untouched'
}

但是使用以下命令在上述项目上进行PUT(更新):

{
    id: hwad0912he109sj(whatever),
    first_status: 'Recalled'
}

应该抛出类似Invalid first_status

的错误

请有人给我一个例子,说明它如何工作。我认为您需要使用类似progressSchema.pre('save'...

的东西

1 个答案:

答案 0 :(得分:1)

猫鼬对此用例具有枚举属性。请参见下面的documentation和示例:

const progressSchema = mongoose.Schema({
    possible_statuses: {
        type: Array
    },
    first_status: {
        type: String,
        enum: ['Untouched', 'In Progress', 'Complete']
    }
});