PUT 方法中的快速验证

编程入门 行业动态 更新时间:2024-10-07 10:16:28

PUT 方法中的<a href=https://www.elefans.com/category/jswz/34/1771431.html style=快速验证"/>

PUT 方法中的快速验证

假设我在 Mongoose 的模式中有 4 个值,我想在更新期间只更新一个字段,而让其他人记住其他三个字段是必需的。我怎样才能通过 EXPRESS VALIDATOR 做到这一点

这是用户模型

import mongoose from "mongoose";

const UserScheme = new mongoose.Schema({
  username: {
    type: String,
    required: true,
    unique: true,
  },
  email: {
    type: String,
    required: true,
    unique: true,
  },
  password: {
    type: String,
    required: true,
  },
  isAdmin: {
    type: Boolean,
    default: false,
  },
  image: {
    type: String,
    required: true,
  },
},{timestamps:true});

export default mongoose.model("User", UserScheme);

这是注册路线,我在这条路线上进行了三个验证

import express from "express";
import { body, validationResult } from "express-validator";
import { Register, Login } from "../controllers/auth.js";
const router = express.Router();

router.post(
  "/register",
  [
    body("username", "Username must contain at least 6 characters").isLength({
      min: 6,
    }),
    body("email", "Email must be a valid email").isEmail(),
    body("password", "Password must contain at least 6 characters").isLength({
      min: 6,
    }),
  ],

  Register
);

这是注册控制器



import User from "../models/User.js";
import bcryptjs from "bcryptjs";
import { validationResult } from "express-validator";
import jwt from "jsonwebtoken";
import cookieParser from "cookie-parser";

// *********************** Regsiter *******************

export const Register = async (req, res, next) => {
  // Finds the validation errors in this request and wraps them in an object with handy functions
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  try {
    const user = await User.findOne({ email: req.body.email });
    if (user) {
      return res
        .status(403)
        .json(
          "Email already registered . Please try with another email address"
        );
    }

    const salt = await bcryptjs.genSalt(10);
    const hashpassword = await bcryptjs.hash(req.body.password, salt);

    const newUser = await User.create({
      username: req.body.username,
      email: req.body.email,
      password: hashpassword,
      image: req.body.image,
    });

    res.status(200).json(newUser);
  } catch (error) {
    res.status(500).json("Internal server error");
  }
};


这是更新路线和控制器

router.put(
  "/updateuser/:id",

  verifyToken,
  updateUser
);

export const updateUser = async (req, res, next) => {

  try {
    const user = await User.findById(req.params.id);
    if (!user) {
      return res.status(404).json("User not found");
    }

    if (req.params.id !== req.user.id) {
      return res.status(404).json("You can only update your account");
    }
    // const {username,email,password}=req.body

    const salt = await bcryptjs.genSalt(10);
    const hashpassword = await bcryptjs.hash(req.body.password, salt);
    const updatedUser = await User.findByIdAndUpdate(
      req.params.id,
      {
        $set: {
          username: req.body.username,
          email: req.body.email,
          password: hashpassword,
          image: req.body.image,
        },
      },
      { $new: true }
    );
    res.status(200).json(updatedUser);
  } catch (error) {
    res.status(500).json("Internal server error");
  }
};


注意:如何应用仅在用户更新电子邮件时才适用的电子邮件验证和密码(字符限制)?如果用户不更新它验证不应该来

回答如下:

更多推荐

PUT 方法中的快速验证

本文发布于:2024-05-30 09:19:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770342.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:快速   方法   PUT

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!