skip to Main Content

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


  1. 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:

    const newEntry = Object.entries(req.body).reduce((obj, [key, value]) => {
      if (value) obj[key] = value
      return obj
    }, {})
    

    In this example, I convert the req.body into an array using Object.entries and iterate over it with the Array.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 simple if check on the value. I then assign the return of the reduce method to the variable newEntry. 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

    Login or Signup to reply.
  2. You could use the set method for Mongoose Schemas:

    const mySchema = new mongoose.Schema(
      {
        myAttribute: {
          type: String,
          set: (attribute: string) => attribute === '' ? undefined : attribute,
        },
      },
      { strict: 'throw' },
    );
    

    This will unset the field if the string equals ''.

    Use this to trim the strings:
    set: (a: string) => a?.trim() === '' ? undefined : a

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search