【问题标题】:How to update user info with specific field in mongodb using node.js如何使用 node.js 在 mongodb 中使用特定字段更新用户信息
【发布时间】:2021-06-01 12:02:12
【问题描述】:

我今天的代码遇到了一些问题。我正在尝试建立一个用户配置文件设置,用户可以在其中更改他们的信息。我的问题如下:

当我更新用户名等特定字段时,我不希望更新其他字段,即电子邮件、名字和姓氏。用户名和电子邮件在数据库中具有唯一属性,如果用户尝试更改用户名,它会显示电子邮件错误,即使用户不想更新电子邮件。

那么,如何在不影响其他字段的情况下更改用户名?

感谢您的宝贵时间。

Node.js

import User from '../model/user.js'
import verify from "../auth/verifyToken.js"

router.put("/user/account/change-user-info", verify,async (req, res) => {
  const { firstName, lastName, username, email } = req.body

  try {
    const user = await User.findOne(req.user)

    // ------------ Firstname validation ------------ //
    if (!firstName || firstName.length < 2 || typeof firstName !== "string")
      return res.status(401).json({
        status: "error",
        massage:
          "Firstname and should not be empty or should be at least 2 characters long!",
      })
    user.firstName = firstName


    // ------------ Lastname Validation ------------ //
    if (!lastName || lastName.length < 2 || typeof LastName !== "string")
      return res.status(401).json({
        status: "error",
        massage:
          "Lastname should not be empty or should be at least 2 characters long!",
      })
    user.lastName = lastName


    // ------------ Email Validation ------------ //
    const emailRegex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/
    const emailExists = await User.findOne({ email })

    if (!email || typeof email !== "string" || !email.match(emailRegex))
      return res.status(400).json({ status: "error", massage: "Invalid email" })
    else if (emailExists) <------ Problem here
      return res
        .status(400)
        .json({ status: "error", massage: "Email already in use." })
    user.email = email


    // ------------ Username Validation --- Problem here ------------//
    const usernameExist = await User.findOne({ username })
    if (!username || typeof username !== "string" || !username.match("^[a-zA-Z0-9_.-]*$"))
      return res
        .status(400)
        .json({ status: "error", massage: "Invalid username." })
    else if (usernameExist) <------ Problem here
      return res
        .status(400)
        .json({ status: "error", massage: "Username is already taken." }) 
    user.username = username

    await user.save()

    res.status(201).json({
      status: "ok",
      massage: "Fields updated successfully!",
    })
  } catch (e) {
    console.log(e)
  }
}

猫鼬

import mongoose from "mongoose"

const userSchema = mongoose.Schema(
  {
    firstName: {
      type: String,
      required: true,
      min: 2,
      max: 45,
    },
    lastName: {
      type: String,
      required: true,
      min: 2,
      max: 45,
    },
    email: {
      type: String,
      required: true,
      min: 6,
      max: 45,
      unique: true,
    },
    username: {
      type: String,
      required: true,
      unique: true,
    },
    password: {
      type: String,
      required: true,
      min: 8,
      max: 100,
    },
    avatar: {
      type: String,
      default: "",
    },
  },
  { timestamp: true }
)

const User = mongoose.model("User", userSchema)

export default User

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    当用户请求更改其详细信息时,检查每个属性以查看是否已更改,然后不要将未更改的属性发送到数据库

    import User from '../model/user.js'
    import verify from "../auth/verifyToken.js"
    
    router.put("/user/account/change-user-info", verify,async (req, res) => {
      const { firstName, lastName, username, email } = req.body
    
      try {
        const user = await User.findOne(req.user)
    
        var updated;
    
        // ------------ Firstname validation ------------ //
        if (!firstName || firstName.length < 2 || typeof email !== "string")
          return res.status(401).json({
            status: "error",
            massage:
              "Firstname and should not be empty or should be at least 2 characters long!",
          })
        // checking if the first name has been changed
        if (user.firstName !== firstName) {
            updated.firstName = firstName
        }
    
    
        // ------------ Lastname Validation ------------ //
        if (!lastName || lastName.length < 2 || typeof email !== "string")
          return res.status(401).json({
            status: "error",
            massage:
              "Lastname should not be empty or should be at least 2 characters long!",
          })
        // checking if the last name has been changed
        if (user.lastName !== lastName) {
            updated.lastName = lastName
        }
    
    
        // ------------ Email Validation ------------ //
        const emailRegex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/
        const emailExists = await User.findOne({ email })
    
        if (!email || typeof email !== "string" || !email.match(emailRegex))
          return res.status(400).json({ status: "error", massage: "Invalid email" })
        else if (emailExists) <------ Problem here
          return res
            .status(400)
            .json({ status: "error", massage: "Email already in use." })
        // checking if the email has been changed
        if (user.email !== email) {
            updated.email = email
        }
    
        // ------------ Username Validation --- Problem here ------------//
        const usernameExist = await User.findOne({ username })
        if (!username || typeof username !== "string" || !username.match("^[a-zA-Z0-9_.-]*$"))
          return res
            .status(400)
            .json({ status: "error", massage: "Invalid username." })
        else if (usernameExist) <------ Problem here
          return res
            .status(400)
            .json({ status: "error", massage: "Username is already taken." }) 
        // checking if the username has been changed
        if (user.username !== username) {
            updated.username= username
        }
    
        // updated variable only contains the updated fields, sending it too the database may solve the problem
        Asset.findOneAndUpdate(req.user, updated, 
        function (updatedUsed) {
            res.status(201).json({
              status: "ok",
              massage: "Fields updated successfully!",
            })
        } catch (e) {
                    console.log(e)
        })
    

    **请检查我是否有任何打字错误**

    【讨论】:

      【解决方案2】:
      import User from '../model/user.js';
      import verify from "../auth/verifyToken.js";
      import _ from lodash;
      
      router.put("/user/account/change-user-info", verify,async (req, res) => {
        const { firstName, lastName, username, email } = req.body;
      
        // check validation check
        if (!_.isNil(firstName) && (firstName.length < 2 || typeof email !== "string")) {
            return res.status(401).json({
              status: "error",
              massage: "Firstname and should not be empty or should be at least 2 characters long!"
            })
         }
      
         if (!_.isNil(lastName) && (lastName.length < 2 || typeof email !== "string")) {
            return res.status(401).json({
              status: "error",
              massage: "LastName and should not be empty or should be at least 2 characters long!"
            })
         }
      
         const emailRegex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
         if (!_.isNil(email) && (typeof email !== "string" || !email.match(emailRegex)) {
            return res.status(401).json({
              status: "error",
              massage: "Invalid email"
            })
         }
      
         // after the basic validation, now check the data from the database
         try {
            const userEmail = await User.findOne({ email });
            if (!_.isEmpty(userEmail)) {
              return res.status(401).json({
                 status: "error",
                 message: "Email already in use"
              });
            }
      
            const userNameExist = await User.findOne({ username });
            if (!_.isEmpty(userNameExist)) {
              return res.status(401).json({
                 status: "error",
                 message: "Username is already taken."
              })
            }
      
            // update the database
            await User.updateOne({_id: req.session.userId}, {req.body});
            res.status(201).json({
               status: "ok",
               message: "Fields updated successfully!",
            })
          } catch (e) {
             console.log(e)
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2015-04-24
        • 2019-10-12
        • 1970-01-01
        • 2015-11-16
        • 1970-01-01
        • 1970-01-01
        • 2023-02-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多