Home > Net >  Not able to update student data
Not able to update student data

Time:10-22

I am trying to update the student data but I'm not ble to update it. In this code, a user needs to login in order to update his/her data and the user's username is the unique id that should match with the student's registrationNumber in order to login.

The error is showing "duplicatekey: registrationNumber" but I'm not updating/modifying the 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)
}

})

CodePudding user response:

instead of passing the username in the parameter, get the id, because it seems like is expected an 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)
}

})
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

findOneAndUpdate first param is an object ( like find or findOne ) so you have to provide an object instead a string

try {
    const registrationNumber = req.user.username
    const student = await Student.findOneAndUpdate({ registrationNumber }, {...req.body})
    res.redirect('/students/profile')
} catch(e) {
    console.log(e)
}

Let check the body (console.log(body)) to make sure body.name or registrationNumber doesn't exists in databse

  • Related