我正在通过 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"
}
}
我使用的架构的完整代码是这样的。
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;
关于如何在架构中使用匹配的说明。