最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

PUT 方法中的快速验证

网站源码admin48浏览0评论

PUT 方法中的快速验证

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");
  }
};


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

回答如下:

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论