0

I am building a project in REST API. One of my models is reservation as described below.

const reservation = new mongoose.Schema({
    customerName: {
        type: String,
        required: true,
        minlength: 3,
        maxlength: 50
    },
    date: { type: Date, required: true },
    message: {
        type: String,
        minlength: 3,
        maxlength: 250
    }
})

I am building a PUT route to update the reservation (shorter version below for simplicity)

router.put('/:id',  async (req, res) => {
    const { customerName, message, date } = req.body;

    const reservation = await Reservation.findByIdAndUpdate(req.params.id, { customerName, message, date: new Date(date) }, {
        new: true
    });

    res.send(reservation);
});

If the client doesn't pass the req.body.message it becomes null in the database. Which makes sense. But what is the way to, instead of overwriting the message to null, just ignore it, and keep the message as it is? There has to be a better way then writing if statements and conditions.

turivishal
  • 34,368
  • 7
  • 36
  • 59
Mickey
  • 30
  • 6
  • Does this answer your question? [Remove blank attributes from an Object in Javascript](https://stackoverflow.com/questions/286141/remove-blank-attributes-from-an-object-in-javascript) – turivishal Aug 27 '21 at 15:07

1 Answers1

0

Rule of thumb : DO NOT accept any input as it is. You should validate the payload.

The cleanest solution is to return 422 status code message if some fields are missing or not validated based on your data format.

For example; if customerName is required field and it should be in a specific format and type but client does not send this field or send the field with empty value or too long or not correct data type then return 422 http status code with error response to explain what the issue is.