发布于 2026-01-06 5 阅读
0

Mongoose Schema 指南 DEV 的全球展示挑战赛,由 Mux 呈现:展示你的项目!

Mongoose Schema 指南

由 Mux 主办的 DEV 全球展示挑战赛:展示你的项目!

Mongoose 是一个用于 Node 的对象数据建模器 (ODM)。它提供了一个简单的验证和查询 API,帮助您与 MongoDB 数据库进行交互。您可以将 Mongoose 理解为一个组织者,当客户端返回数据时,Mongoose 会根据您的模型(模式)验证并组织数据。您将始终清楚地了解数据库中存储的数据及其存储方式。让我们来看一个例子。

什么是模式?

上面我提到了结构和验证,这就是你的 Mongoose schema。假设你的页面上有一个注册表单。你可能不想允许用户名中包含某些字符,或者你想确保存储在数据库中的电子邮件地址有效。

本教程假设您知道如何使用 NPM 或 YARN 将 mongoose 添加到您的项目中。

首先,我们需要引入 mongoose。

//import mongoose NPM module
import mongoose from "mongoose";

// Save a reference to the Schema constructor `mongoose.model`
let Schema = mongoose.Schema;
Enter fullscreen mode Exit fullscreen mode

上面我们使用模式构造函数mongoose.schema并将其保存在一个名为 的变量中Schema

下面我们创建一个new Schema,并将其命名为UserSchema

const UserSchema = new Schema({
  // `username` must be of type String
  // `username` will trim leading and trailing whitespace before it's saved
  // `username` is a required field and throws a custom error message if not supplied
  username: {
    type: String,
    trim: true,
    required: "Username is Required"
  },
  // `password` must be of type String
  // `password` will trim leading and trailing whitespace before it's saved
  // `password` is a required field and throws a custom error message if not supplied
  // `password` uses a custom validation function to only accept values 6 characters or more
  password: {
    type: String,
    trim: true,
    required: "Password is Required",
    validate: [
      function(input) {
        return input.length >= 6;
      },
      "Password should be longer."
    ]
  },
  // `email` must be of type String
  // `email` must be unique
  // `email` must match the regex pattern below and throws a custom error message if it does not
  email: {
    type: String,
    unique: true,
    match: [/.+@.+\..+/, "Please enter a valid e-mail address"]
  }
});
Enter fullscreen mode Exit fullscreen mode

上面,我们告诉模式(Schema)如何验证和存储数据。我们实际上是在说,我期望返回以下信息。您的用户名必须是字符串,系统会自动去除字符串前后所有的空格,如果您尝试提交空白用户名,则会抛出错误。

创建模型并导出

// This creates our model from the above schema, using mongoose's model method
let User = mongoose.model("User", UserSchema);

// Export the User model
module.exports = User;
Enter fullscreen mode Exit fullscreen mode

使用模型

替代文字

所以,你已经在前端创建了一个简单的登录功能,并在后端创建了一个 POST 路由,用于通过 Mongoose 将数据存储到我们的 MongoDB 数据库中。请看下面的 POST 路由代码。我们创建了一个new实例User并传入参数req.body。我们create在数据库中创建了一个新文档,并将结果返回user给客户端;如果信息无效,则返回一个错误。

const User = require("./userModel.js");

app.post("/submit", function(req, res) {
         /*req.body {
             username: "mongod", 
             password: "pass123", 
             email: "none@none.com"
            } 
  Create a new user using req.body (this data came from the client)*/
  let user = new User(req.body);

  User.create(user)
    .then(function(dbUser) {
      // If saved successfully, send the the new User document to the client
      res.json(dbUser);
    })
    .catch(function(err) {
      // If an error occurs, send the error to the client
      res.json(err);
    });
});
Enter fullscreen mode Exit fullscreen mode

结论

锵锵!我们刚刚创建了一个 Mongoose schema,并用它来验证存储在 MongoDB 中的数据。这是一个构建 MongoDB 时非常棒的工具,您可以完全控制哪些数据会进入数据库以及数据的存储方式。感谢阅读!

文章来源:https://dev.to/mcarpenter/mongoose-schemas-guide-fh