我正在嘗試更新學生資料,但無法更新。在這段代碼中,用戶需要登錄才能更新他/她的資料,并且用戶的用戶名是唯一的 id,應該與學生的注冊號匹配才能登錄。
錯誤顯示“duplicatekey:registrationNumber”,但我沒有更新/修改registrationNumber。
router.get('/edit', isLoggedIn, async(req, res) => {
const registrationNumber = req.user.username
const student = await
Student.findOne({registrationNumber})
res.render('students/edit', { student })
})
router.put('/edit', isLoggedIn, async(req, res) => {
try {
const registrationNumber = req.user.username
const student = await
Student.findOneAndUpdate(registrationNumber, {...req.body})
res.redirect('/students/profile')
} catch(e) {
console.log(e)
}
})
uj5u.com熱心網友回復:
findOneAndUpdate第一個引數是一個物件(像findor findOne)所以你必須提供一個物件而不是一個字串
try {
const registrationNumber = req.user.username
const student = await Student.findOneAndUpdate({ registrationNumber }, {...req.body})
res.redirect('/students/profile')
} catch(e) {
console.log(e)
}
讓我們檢查正文 (console.log(body)) 以確保 body.name 或 registrationNumber 在資料庫中不存在
uj5u.com熱心網友回復:
不要在引數中傳遞用戶名,而是嘗試獲取 id,因為它似乎在期待一個 id。
router.put('/edit', isLoggedIn, async(req, res) => {
try {
const registrationNumber = req.params.edit
const student = await Student.findOneAndUpdate(registrationNumber, {...req.body})
res.redirect('/students/profile')
} catch(e) {
console.log(e)
}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/336050.html
上一篇:fetch和post的關系
