当我更新用户对象的一个值时,数据库中的所有其他值都被删除。我该怎么办?
When I update one value of a users object, all other values are deleted in database. What can I do about this?
我正在与一组开发人员一起从事一个学校项目。我们创建了一个页面,用户可以在其中拥有个人资料,并且可以更新该个人资料。当用户更新其信息时,我们遇到了一个错误。例如,如果我更新了我的城市,那么关于我的用户的所有其他信息都会消失。我也必须更新其他字段,否则数据库将只存储我最近更新的城市。
我想要的是除了我更新用户时更改的信息之外,还保存了我创建用户时填写的信息。
更新前: {"username":"bobox","email":"bobox@hotmail.com","password":"test234","gender":"Man","age":"17","city":"Jönköping","games":"Battlefield V","usernameDiscord":"bigbox","usernameSteam":"bigbox","usernameOrigin":"bobox","_id":"wTs8IyRmcA40f3VN"}
更新后: {"username":"bobox","email":"bobox@hotmail.com","password":"test234","gender":"","age":"","city":"New York","games":"","usernameDiscord":"","usernameSteam":"","usernameOrigin":"","_id":"wTs8IyRmcA40f3VN"}
这是代码。我感谢所有的帮助。如果您还有其他需要了解的,请告诉我。
更新用户:
script.js
async function updateUser(age, city, gender, games, discord, steam, origin) {
const id = localStorage.getItem("userId")
const response = await fetch('http://localhost:8080/users/' + id, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
age: age,
city: city,
gender: gender,
games: games,
usernameDiscord: discord,
usernameSteam: steam,
usernameOrigin: origin
})
})
console.log(response)
const data = await response.json()
console.log(data)
}
function updateUsersIndex() {
let updateProfileBtn = document.querySelector(".Profile-Right__Update")
console.log(updateProfileBtn)
updateProfileBtn.addEventListener("click", async(event) => {
console.log("hej")
event.preventDefault()
const age = document.querySelector(".Age__Input").value
const city = document.querySelector(".City__Input").value
const gender = document.querySelector(".Gender__Input").value
const discord = document.querySelector(".Discord__Input").value
const steam = document.querySelector(".Steam__Input").value
const origin = document.querySelector(".Origin__Input").value
const games = document.querySelector(".Profile-Right__Select-Game").value
const hidden = document.querySelector(".hidden")
const updateUsers = await updateUser(age, city, gender, games, discord, steam, origin)
})
}
updateUsersIndex()
let profileUpdateBackBtn = document.querySelector(".Profile-Right__Back")
profileUpdateBackBtn.addEventListener("click", async(event) => {
event.preventDefault()
let updateProfile = document.querySelector(".Update-Profile")
let profile = document.querySelector(".Profile__Wrappe")
profile.classList.toggle("Hidden")
updateProfile.classList.toggle("Hidden")
})
app.js:
app.patch('/users/:id', async(req, res) => {
const result = await collectionsNEDB.users.update({ _id: req.params.id }, {
$set: {
"age": req.body.age,
"city": req.body.city,
"gender": req.body.gender,
"games": req.body.games,
"usernameDiscord": req.body.usernameDiscord,
"usernameSteam": req.body.usernameSteam,
"usernameOrigin": req.body.usernameOrigin
}
})
console.log(req.params.id)
res.json(result)
})
创建用户:
script.js
async function createUser(username, email, password, repeatPassword, games, usernameDiscord, usernameSteam, usernameOrigin) {
const response = await fetch('http://localhost:8080/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: username,
email: email,
password: password,
repeatPassword,
games: games,
usernameDiscord: usernameDiscord,
usernameSteam: usernameSteam,
usernameOrigin: usernameOrigin
})
})
console.log(response)
const data = await response.json()
if (response.status == 200) {
console.log(data.message)
if (data.message == "SUCCESS") {
console.log("Great")
let Success = document.querySelector(".Success")
Success.innerHTML = "Användare skapad!"
alert("Användare skapad!")
}
} else {
const data = await response.json()
const p = document.querySelector("p")
p.innerHTML = ""
for (let i = 0; i < data.errors.length; i++) {
const error = data.errors[i]
console.log(data.errors)
switch (error) {
case "ERROR_USER_ALREADY_EXISTS":
const hidden = document.querySelector(".Error")
hidden.classList.toggle("Hidden")
hidden.innerHTML = "Användarnamnet existerar redan!"
break;
case "ERROR_EMAIL_ALREADY_EXISTS":
const hiddenEmail = document.querySelector(".Error__Email")
hiddenEmail.classList.toggle("Hidden__Email")
hiddenEmail.innerHTML = "E-mail existerar redan!"
break;
case "ERROR_PASSWORD_MISMATCH":
const hiddenPassword = document.querySelector(".Error__Password")
hiddenPassword.classList.toggle("Hidden__Password")
hiddenPassword.innerHTML = "Lösenordet matchar inte"
break;
}
}
}
}
function init() {
let form = document.querySelector("#Reg-Form-1")
form.addEventListener("submit", async(event) => {
event.preventDefault()
const username = form.querySelector(".username").value
const email = form.querySelector(".email").value
const password = form.querySelector(".password").value
const repeatPassword = form.querySelector(".repeat-password").value
const games = form.querySelector(".gejms").value
const usernameDiscord = form.querySelector(".usernameDiscord").value
const usernameSteam = form.querySelector(".usernameSteam").value
const usernameOrigin = form.querySelector(".usernameOrigin").value
const hidden = document.querySelector(".hidden")
const createUsers = await createUser(username, email, password, repeatPassword, games, usernameDiscord, usernameSteam, usernameOrigin)
})
}
init()
app.js:
app.post("/register", async(req, res) => {
let user, email
if (process.env.NODE_ENV == "development") {
user = await collectionsNEDB.users.find({ username: req.body.username })
email = await collectionsNEDB.users.find({ email: req.body.email })
} else {
dataUser = await Database.collections.users.find({ username: req.body.username })
dataEmail = await Database.collections.users.find({ email: req.body.email })
user = await dataUser.toArray()
email = await dataEmail.toArray()
}
let errors = []
if (req.body.password !== req.body.repeatPassword) {
errors.push("ERROR_PASSWORD_MISMATCH")
} else if (user == false) {
if (email == false) {
let newUser = {
username: req.body.username,
email: req.body.email,
password: req.body.password,
gender: "",
age: "",
city: "",
games: req.body.games,
usernameDiscord: req.body.usernameDiscord,
usernameSteam: req.body.usernameSteam,
usernameOrigin: req.body.usernameOrigin
}
if (process.env.NODE_ENV == "development") {
const result = await collectionsNEDB.users.insert(newUser)
res.status(200).json({ message: "SUCCESS" })
} else {
let db = await Database.connect()
let users = db.collection("users")
const result = await users.insert(newUser)
res.status(200).json({ message: "SUCCESS" })
console.log(result)
}
} else {
errors.push("ERROR_EMAIL_ALREADY_EXISTS")
}
} else {
errors.push("ERROR_USER_ALREADY_EXISTS")
}
if (errors.length > 0) {
res.status(400).json({ errors: errors })
}
})
问题是空的表单字段将用空字符串覆盖现有的数据库字段。
解决方案是用所有当前值预填充表单:在显示 "update user" 表单的路由中,加载用户信息并将其传递给模板,然后将其插入 <input>
s 为 value
.
这也使用户能够再次删除信息,只需清空字段并提交表单即可。
最后说明:你应该可以替换
$set: {
"age": req.body.age,
"city": req.body.city,
"gender": req.body.gender,
"games": req.body.games,
"usernameDiscord": req.body.usernameDiscord,
"usernameSteam": req.body.usernameSteam,
"usernameOrigin": req.body.usernameOrigin
}
与
$set: req.body
我正在与一组开发人员一起从事一个学校项目。我们创建了一个页面,用户可以在其中拥有个人资料,并且可以更新该个人资料。当用户更新其信息时,我们遇到了一个错误。例如,如果我更新了我的城市,那么关于我的用户的所有其他信息都会消失。我也必须更新其他字段,否则数据库将只存储我最近更新的城市。
我想要的是除了我更新用户时更改的信息之外,还保存了我创建用户时填写的信息。
更新前: {"username":"bobox","email":"bobox@hotmail.com","password":"test234","gender":"Man","age":"17","city":"Jönköping","games":"Battlefield V","usernameDiscord":"bigbox","usernameSteam":"bigbox","usernameOrigin":"bobox","_id":"wTs8IyRmcA40f3VN"}
更新后: {"username":"bobox","email":"bobox@hotmail.com","password":"test234","gender":"","age":"","city":"New York","games":"","usernameDiscord":"","usernameSteam":"","usernameOrigin":"","_id":"wTs8IyRmcA40f3VN"}
这是代码。我感谢所有的帮助。如果您还有其他需要了解的,请告诉我。
更新用户: script.js
async function updateUser(age, city, gender, games, discord, steam, origin) {
const id = localStorage.getItem("userId")
const response = await fetch('http://localhost:8080/users/' + id, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
age: age,
city: city,
gender: gender,
games: games,
usernameDiscord: discord,
usernameSteam: steam,
usernameOrigin: origin
})
})
console.log(response)
const data = await response.json()
console.log(data)
}
function updateUsersIndex() {
let updateProfileBtn = document.querySelector(".Profile-Right__Update")
console.log(updateProfileBtn)
updateProfileBtn.addEventListener("click", async(event) => {
console.log("hej")
event.preventDefault()
const age = document.querySelector(".Age__Input").value
const city = document.querySelector(".City__Input").value
const gender = document.querySelector(".Gender__Input").value
const discord = document.querySelector(".Discord__Input").value
const steam = document.querySelector(".Steam__Input").value
const origin = document.querySelector(".Origin__Input").value
const games = document.querySelector(".Profile-Right__Select-Game").value
const hidden = document.querySelector(".hidden")
const updateUsers = await updateUser(age, city, gender, games, discord, steam, origin)
})
}
updateUsersIndex()
let profileUpdateBackBtn = document.querySelector(".Profile-Right__Back")
profileUpdateBackBtn.addEventListener("click", async(event) => {
event.preventDefault()
let updateProfile = document.querySelector(".Update-Profile")
let profile = document.querySelector(".Profile__Wrappe")
profile.classList.toggle("Hidden")
updateProfile.classList.toggle("Hidden")
})
app.js:
app.patch('/users/:id', async(req, res) => {
const result = await collectionsNEDB.users.update({ _id: req.params.id }, {
$set: {
"age": req.body.age,
"city": req.body.city,
"gender": req.body.gender,
"games": req.body.games,
"usernameDiscord": req.body.usernameDiscord,
"usernameSteam": req.body.usernameSteam,
"usernameOrigin": req.body.usernameOrigin
}
})
console.log(req.params.id)
res.json(result)
})
创建用户: script.js
async function createUser(username, email, password, repeatPassword, games, usernameDiscord, usernameSteam, usernameOrigin) {
const response = await fetch('http://localhost:8080/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: username,
email: email,
password: password,
repeatPassword,
games: games,
usernameDiscord: usernameDiscord,
usernameSteam: usernameSteam,
usernameOrigin: usernameOrigin
})
})
console.log(response)
const data = await response.json()
if (response.status == 200) {
console.log(data.message)
if (data.message == "SUCCESS") {
console.log("Great")
let Success = document.querySelector(".Success")
Success.innerHTML = "Användare skapad!"
alert("Användare skapad!")
}
} else {
const data = await response.json()
const p = document.querySelector("p")
p.innerHTML = ""
for (let i = 0; i < data.errors.length; i++) {
const error = data.errors[i]
console.log(data.errors)
switch (error) {
case "ERROR_USER_ALREADY_EXISTS":
const hidden = document.querySelector(".Error")
hidden.classList.toggle("Hidden")
hidden.innerHTML = "Användarnamnet existerar redan!"
break;
case "ERROR_EMAIL_ALREADY_EXISTS":
const hiddenEmail = document.querySelector(".Error__Email")
hiddenEmail.classList.toggle("Hidden__Email")
hiddenEmail.innerHTML = "E-mail existerar redan!"
break;
case "ERROR_PASSWORD_MISMATCH":
const hiddenPassword = document.querySelector(".Error__Password")
hiddenPassword.classList.toggle("Hidden__Password")
hiddenPassword.innerHTML = "Lösenordet matchar inte"
break;
}
}
}
}
function init() {
let form = document.querySelector("#Reg-Form-1")
form.addEventListener("submit", async(event) => {
event.preventDefault()
const username = form.querySelector(".username").value
const email = form.querySelector(".email").value
const password = form.querySelector(".password").value
const repeatPassword = form.querySelector(".repeat-password").value
const games = form.querySelector(".gejms").value
const usernameDiscord = form.querySelector(".usernameDiscord").value
const usernameSteam = form.querySelector(".usernameSteam").value
const usernameOrigin = form.querySelector(".usernameOrigin").value
const hidden = document.querySelector(".hidden")
const createUsers = await createUser(username, email, password, repeatPassword, games, usernameDiscord, usernameSteam, usernameOrigin)
})
}
init()
app.js:
app.post("/register", async(req, res) => {
let user, email
if (process.env.NODE_ENV == "development") {
user = await collectionsNEDB.users.find({ username: req.body.username })
email = await collectionsNEDB.users.find({ email: req.body.email })
} else {
dataUser = await Database.collections.users.find({ username: req.body.username })
dataEmail = await Database.collections.users.find({ email: req.body.email })
user = await dataUser.toArray()
email = await dataEmail.toArray()
}
let errors = []
if (req.body.password !== req.body.repeatPassword) {
errors.push("ERROR_PASSWORD_MISMATCH")
} else if (user == false) {
if (email == false) {
let newUser = {
username: req.body.username,
email: req.body.email,
password: req.body.password,
gender: "",
age: "",
city: "",
games: req.body.games,
usernameDiscord: req.body.usernameDiscord,
usernameSteam: req.body.usernameSteam,
usernameOrigin: req.body.usernameOrigin
}
if (process.env.NODE_ENV == "development") {
const result = await collectionsNEDB.users.insert(newUser)
res.status(200).json({ message: "SUCCESS" })
} else {
let db = await Database.connect()
let users = db.collection("users")
const result = await users.insert(newUser)
res.status(200).json({ message: "SUCCESS" })
console.log(result)
}
} else {
errors.push("ERROR_EMAIL_ALREADY_EXISTS")
}
} else {
errors.push("ERROR_USER_ALREADY_EXISTS")
}
if (errors.length > 0) {
res.status(400).json({ errors: errors })
}
})
问题是空的表单字段将用空字符串覆盖现有的数据库字段。
解决方案是用所有当前值预填充表单:在显示 "update user" 表单的路由中,加载用户信息并将其传递给模板,然后将其插入 <input>
s 为 value
.
这也使用户能够再次删除信息,只需清空字段并提交表单即可。
最后说明:你应该可以替换
$set: {
"age": req.body.age,
"city": req.body.city,
"gender": req.body.gender,
"games": req.body.games,
"usernameDiscord": req.body.usernameDiscord,
"usernameSteam": req.body.usernameSteam,
"usernameOrigin": req.body.usernameOrigin
}
与
$set: req.body