Mongoose Schema:强制执行互斥键
Mongoose Schema: enforcing mutually exclusive keys
我的 API 将收到的数据包含两个密钥之一,option1
或 option2
,但不会同时包含这两个密钥。
我想在我的 mongoose 模式中强制执行该行为,但没有发现任何可以做到这一点的方法,有没有办法 link 两个键并确保其中一个(并且只有一个)存在?
示例代码:
const exampleSchema = new mongoose.Schema({
custRef: {
type: String,
required: true,
trim: true
},
option1: {
type: Number
},
option2: {
type: Number
}
});
示例JSON 1:
{
"custRef": "abc123",
"option1": 456
}
示例JSON 2:
{
"custRef": "abc789",
"option2": 010
}
您可以像这样使用预验证挂钩:
(请注意,为简单起见,我删除了 custRef 字段)
const mongoose = require("mongoose");
const exampleSchema = new mongoose.Schema({
option1: {
type: Number
},
option2: {
type: Number
}
});
exampleSchema.pre("validate", function(next) {
//console.log(this);
if (this.option1 && this.option2) {
let err = new Error("Both options not allowed");
err.status = 400;
next(err);
} else if (!(this.option1 || this.option2)) {
let err = new Error("One of the options is required");
err.status = 400;
next(err);
}
next();
});
const Example = mongoose.model("Example", exampleSchema);
const example = new Example({});
example.validate().catch(err => {
console.log(err.message);
});
这可能不适用于更新操作,所以要小心。
文档:
我的 API 将收到的数据包含两个密钥之一,option1
或 option2
,但不会同时包含这两个密钥。
我想在我的 mongoose 模式中强制执行该行为,但没有发现任何可以做到这一点的方法,有没有办法 link 两个键并确保其中一个(并且只有一个)存在?
示例代码:
const exampleSchema = new mongoose.Schema({
custRef: {
type: String,
required: true,
trim: true
},
option1: {
type: Number
},
option2: {
type: Number
}
});
示例JSON 1:
{
"custRef": "abc123",
"option1": 456
}
示例JSON 2:
{
"custRef": "abc789",
"option2": 010
}
您可以像这样使用预验证挂钩:
(请注意,为简单起见,我删除了 custRef 字段)
const mongoose = require("mongoose");
const exampleSchema = new mongoose.Schema({
option1: {
type: Number
},
option2: {
type: Number
}
});
exampleSchema.pre("validate", function(next) {
//console.log(this);
if (this.option1 && this.option2) {
let err = new Error("Both options not allowed");
err.status = 400;
next(err);
} else if (!(this.option1 || this.option2)) {
let err = new Error("One of the options is required");
err.status = 400;
next(err);
}
next();
});
const Example = mongoose.model("Example", exampleSchema);
const example = new Example({});
example.validate().catch(err => {
console.log(err.message);
});
这可能不适用于更新操作,所以要小心。
文档: