I have the following schema:
const mySchema = new mongoose.Schema({
x: String,
y: String
})
when a user from the front-end requests in his body:
req.body = {
'x' : '',
'y': ''
}
this results in creating a field in MongoDB, but with an empty string.
I need a way to prevent this behavior by setting the empty strings to be undefined somehow.
Is there such an option in Mongoose? or do I have to predict my own middlewares for that?
2
Answers
You don’t need mongoose, or a middleware to handle this. You can just write a quick few lines to check for empty values and exclude them from the MongoDB write operation.
Ex:
In this example, I convert the
req.body
into an array usingObject.entries
and iterate over it with theArray.reduce
method, wherein I add key:value pairs to a new object if there is a value to add. Since an empty string value is falsey I can do a simpleif
check on the value. I then assign the return of the reduce method to the variablenewEntry
. Then I would then take the new entry and create the MongoDB document with it.This could be extracted into a helper method and reused in any of your routes that need to check remove empty values from an object.
Docs on Array.reduce
Docs on Object.entries
You could use the
set
method for Mongoose Schemas:This will unset the field if the string equals
''
.Use this to trim the strings:
set: (a: string) => a?.trim() === '' ? undefined : a