【发布时间】: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
【问题讨论】: