2

I'm trying to create a validator that will display an error message when a user tries to update a column that doesn't exist in the database schema. I'm using PostgreSQL. When I send a request with the correct allowed updates it returns an error: 'Invalid updates' What am I missing?

const updateQuestion = async (req, res) => {

const updates = Object.keys(req.body)
const allowedUpdates = ['title', 'text, questionCateg']
const isValidOperation = updates.every((update) => allowedUpdates.includes(update))

if (!isValidOperation) {
    return res.status(400).send({
        error: 'Invalid updates'
    })
}

try {
    const {
        id
    } = req.params;
    const {
        title,
        text,
        questionCateg
    } = req.body


    const updateQuestion = await pool.query("UPDATE Questions SET title = $1, text = $2, questionCateg = $3 WHERE id =$4",
        [title, text, questionCateg, id]);
    console.log(updateQuestion)
    res.json('Question updated')
} catch (e) {
    res.status(400).send()



}
}

Route:

router.patch('/questions/:id', updateQuestion)

Thanks in advance!

kawadhiya21
  • 2,458
  • 21
  • 34

1 Answers1

0

What do you see when you console.log(req.body) ? you should concentrate on that updates array.

You can use body-parser in your app.js or express.json() middleware This way you can succesfully receive your items that you are sending to your backend.

You can send the updates in post request body with the key updates. Then you can parse it like req.body.updates (updates is an array)

You can use body parser like this

app.use(bodyParser.urlencoded({ 
     extended: true 
}));

or app.use(express.json())

you can see further information in this post express.json() and express.urlencoded()

forth
  • 55
  • 1
  • 9