zulu_papa
zulu_papa

Reputation: 415

Why NodeJS put request doesn't update the property, it only returns the id of the object

There is a slight problem with updating the object via put request in my code. When i send put request with postman, request returns only the id of the genre object. Genre object has an id and a name properties.

app.put('/vidly/genres/:id', (req, res) => {

    const genre = genres.find(g => g.id === parseInt(req.params.id));
    if (!genre) return res.status(404).send('The genre was not found.');
  
    const result = validateGenre(req.body.name); 
    if (result.error) return res.status(400).send(error.details[0].message);

    genre.name = req.body.name;
    res.send(genre);
  });

  function validateGenre(genre) {
    const schema = Joi.object({
      name: Joi.string().min(3).required()
    });
    
    return schema.validate(genre);
    };

I am struggling to find a proper solution. Any help would be useful. If somebody could explain what am i doing wrong so i can have better understanding of this problem. Thank you very much

Upvotes: 1

Views: 410

Answers (1)

Matt
Matt

Reputation: 74630

The example is validating if req.body.name has an additional .name property. The schema also doesn't require the base object, so in this case when req.body.name is not defined, the validation passed without even checking for properties.

The schema should make the object itself required.

const schema = Joi.object({
  name: Joi.string().min(3).required()
}).required()

Then the body can be validated

const result = validateGenre(req.body)
if (result.error) {
  return res.status(400).send(result.error.details[0].message);
}

Or possibly the constructed genre

genre.name = req.body.name
const result = validateGenre(genre)

Upvotes: 1

Related Questions