当我使用node.js时,数据库表没有在postgres中更新

rslzwgfq  于 11个月前  发布在  Node.js
关注(0)|答案(2)|浏览(126)

我正在构建CRUD应用程序,我能够读取和删除数据,但我无法为特定路由更新数据库表中的数据,而且当我试图更新id为1的表中的数据时,它会更新所有id中的数据

app.get('/doctor/edit/:id', async (req, res) => {
    const id = req.params.id;
    //console.log(id);
    const data = await doctor.getDoctorById(id);
    res.render('editDoctor', { data });
});
//update doctor
app.post('/doctor/edit/:id', async (req, res) => {
    const data = req.body;
    const id = req.params.id; // Get the 'id' from the URL parameters
    console.log(data);
    console.log(id);
    try {
        await doctor.updateDoctor(data, id); // Pass the 'id' to the updateDoctor function
        res.redirect('/doctor');
    } catch (error) {
        console.log('Error updating patient:', error);
        res.status(500).send('Internal Server Error');
    }
});
// function to update the information
const updateDoctor = async (updatedData) => {
    const { id, name, specialization, contact, appointment } = updatedData;
    const query = `
    UPDATE doctor
    SET name = $2, specialization = $3, contact = $4, appointment = $5
    WHERE id = $1`;
    const values = [id, name, specialization, contact, appointment]; // Correct order of values
    await pool.query(query, values);
};

字符串
我在前端使用ejs,我希望现有的医生信息应该更新与此代码,但我收到的数据,但它没有在数据库中更新。

oymdgrw7

oymdgrw71#

app.post('/doctor/edit/:id', async (req, res) => {
    const id = req.params.id;
    const updatedData = req.body;
    try {
        await doctor.updateDoctor(id, updatedData);
        res.redirect('/doctor');
    } catch (error) {
        console.log('Error updating doctor:', error);
        res.status(500).send('Internal Server Error');
    }
});
  
const updateDoctor = async (id, updatedData) => {
            const { name, specialization, contact, appointment } = updatedData;
            const query = `
                UPDATE doctor
                SET name = $2, specialization = $3, contact = $4, appointment = $5
                WHERE id = $1`;
            const values = [id, name, specialization, contact, appointment];
            await pool.query(query, values);
        };

字符串

8dtrkrch

8dtrkrch2#

尝试在常量查询中使用反引号,并尝试为查询方法执行添加excpeiton处理块,即(error,results)=> {}。
也就是说,

const updateUser = (request, response) => {
  const id = parseInt(request.params.id)
  const { name, email } = request.body

  pool.query(
    'UPDATE users SET name = $1, email = $2 WHERE id = $3',
    [name, email, id],
    (error, results) => {
      if (error) {
        console.log("error"+error);
        throw error
      }
      response.status(200).send(`User modified with ID: ${id}`)
    }
  )
}

字符串

相关问题