I have a collection model like this:
const Task = mongoose.model('Task', {
description: {
type: String,
trim: true,
required: true
},
completed: {
type: Boolean,
default: false
}
})
Currently, When a user tries to update a document using the API, any field that is not in the schema will be ignored, and the document will be updated. I want to throw an error if the user sends an update request to the API with a field that is not available in the database.
if I have a task with id of 12345
in the database:
{
_id: 12345,
description: "Buy cheese."
completed: false
}
and a user sends an update query to the API for a the task:
id = '12345'
updates = {
description: 'Buy Milk',
due: '1 Week' //<-- Invalid Field
}
And I use this object to update the document:
await Task.findByIdAndUpdate(id, updates)
mongoose completely ignores the invalid due
field and updates the document with the new description
field.
Is there a clean way to avoid this sort of invalid update requests?