gpt4 book ai didi

node.js - Mongoose :简单的自定义验证功能不起作用

转载 作者:可可西里 更新时间:2023-11-01 10:41:03 26 4
gpt4 key购买 nike

背景

我正在为国家/地区定义一个 Mongoose 架构,我在其中存储国家/地区名称及其 ISO alpha2ISO alpha3代码。

这些 ISO 代码只是国家名称的缩写。例如,西类牙是 ES,美国是 US,等等。

目标

我的目标是进行架构验证,以便在向集合中插入国家/地区时代码具有正确数量的字母。

一个 ISO alpha2 代码只能有 2 个字符,而一个 ISO alpha3 代码可以有 3 个。

问题

为了实现这一点,我有一个验证函数来检查给定代码的大小是否正确:

const hasValidFormat = (val, size) => val.length === size;  

我正在尝试使用这个函数作为我的验证器:

"use strict";

const mongoose = require("mongoose");

const hasValidFormat = (val, size) => val.length === size;

const countrySchema = {
name: { type: String, required: true },
isoCodes:{
alpha2: {
type: String,
required:true,
validate: {
validator: hasValidFormat(val, 2),
message: "Incorrect format for alpha-2 type ISO code."
}
},
alpha3: {
type: String,
validate: {
validator: hasValidFormat(val, 3),
message: "Incorrect format for alpha-3 type ISO code."
}
}
}
};


module.exports = new mongoose.Schema(countrySchema);
module.exports.countrySchema = countrySchema;

问题是我遇到错误 val is not defined 并且代码无法运行。这令人困惑,因为根据 Mongoose docs for custom validators , validator 字段是一个函数!

然而

如果我把之前的代码改成:

"use strict";

const mongoose = require("mongoose");

const hasValidFormat = (val, size) => val.length === size;

const countrySchema = {
name: { type: String, required: true },
isoCodes:{
alpha2: {
type: String,
required:true,
validate: {
validator: val => hasValidFormat(val, 2),
message: "Incorrect format for alpha-2 type ISO code."
}
},
alpha3: {
type: String,
validate: {
validator: val => hasValidFormat(val, 3),
message: "Incorrect format for alpha-3 type ISO code."
}
}
}
};


module.exports = new mongoose.Schema(countrySchema);
module.exports.countrySchema = countrySchema;

它会起作用的!

问题

有人能解释一下为什么第一个例子不起作用,而第二个例子起作用吗?

最佳答案

这是因为validator 函数将只有一个参数。

根据文档,如果 validator 函数有两个参数,mongoose 将假定第二个参数是一个回调。

"Custom validators can also be asynchronous. If your validator function takes 2 arguments, mongoose will assume the 2nd argument is a callback."

来源:http://mongoosejs.com/docs/validation.html

您的第一个代码失败主要是因为 Mongoose 将其视为异步验证,但事实并非如此。作为一条黄金法则,验证函数应该是内联的。

您可以使用更接近的函数来实现您正在寻找的行为,就像在第二个代码示例中一样。

谢谢,

关于node.js - Mongoose :简单的自定义验证功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43251725/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com