我正在从这个youtube视频Next.js 13 Full Course 2023中学习Next.js,在这里他讲述了“匹配”,他用它作为数据的一个要求,通过在那里添加一些代码来匹配他给予的一些属性。
username: {
type: String,
required : [true, 'username is required'],
match: [/^(?=.{8,20}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$/, "Username invalid, it should contain 8-20 alphanumeric letters and be unique!"],
},
我想知道更多关于这种方式的写作比赛,以及如何改变或使自己的,但我找不到任何文件或解释。请帮助我学习如何使用它。我目前使用Nextjs和MongoDB作为数据库和Mongoose。如果需要的话,这里有一个我的pakage.json的副本。
{
"name": "surveysnap",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"autoprefixer": "10.4.15",
"express": "^4.18.2",
"mongoose": "^7.5.2",
"next": "13.4.19",
"next-auth": "^4.23.1",
"postcss": "8.4.28",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-icons": "^4.10.1",
"tailwindcss": "3.3.3"
}
}
我使用的Schema的完整代码是这样的。
import { Schema, model, models } from "mongoose";
// models is the collection of all the model that is associated with the mongoose library
const UserSchema = new Schema({
email: {
type : String,
unique : [true, 'email already in use'],
required : [true, 'email already in use'],
},
username: {
type: String,
required : [true, 'username is required'],
match: [/^(?=.{8,20}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$/, "Username invalid, it should contain 8-20 alphanumeric letters and be unique!"],
},
password: {
type: String,
match: [/^(?=.{8,20}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$/, "Password invalid, it should contain 8-20 alphanumeric letters and be unique!"],
},
image: {
type: String,
},
membership: {
type: String,
required : [true, 'membership is information is required'],
},
survey_created: {
type: Number,
},
survey_answered: {
type: Number,
},
snap_points: {
type: Number,
},
});
const User = models.User || model("User", UserSchema);
// if a "User" already exists, models assign the existing one to avoid redefining model and ensuring the existing one be used.
// Otherwise it will create a new one.
export default User;
解释如何在Schema中使用Match。
1条答案
按热度按时间6yoyoihd1#
在Mongoose中,match用于为使用它的属性的模式值设置regexp验证器。
第一个参数是Regular Expression,第二个参数是匹配失败时返回给用户的消息。
在您的示例中,这是RegExp:
这是一条信息:
无论传递什么值,都将根据正则表达式进行测试。你可以操纵正则表达式,直到你满意为止,但它并不繁琐,所以请阅读RegExp并做一些测试,以确保它做你认为它做的事情,例如:
空字符串、未定义和空值总是通过匹配验证器。如果您需要这些值,请同时启用所需的验证器。