Patrickkx
Patrickkx

Reputation: 1870

Moongose - got a schema but its being ignored somehow

I got a moongose schema -

mongoose.Schema(
   {
      companyName: {
         type: String,
         required: true
      }
   },
   {
      companyEmail: {
         type: String,
         required: true
      }
   },
   {
      companySite: {
         type: String,
         required: true
      }
   })

If I test it in e.g. Postman, if I submit empty object it properly throws an error:

"Path 'companyName' is required.",

However, if I enter just the companyName, the post request is being properly processed, even if I didnt enter companyEmail or companySite and they are required. Looking for help.

Upvotes: 0

Views: 37

Answers (2)

d_shiv
d_shiv

Reputation: 1790

The mongoose.Schema function takes only one argument describing the data model. However, in JS the number of arguments isn't validated at time of function call, so your call with three arguments doesn't fail just that last two are simply ignored. Effectively the schema created by your code only contains companyName field.

You should create your schema like this to make it validate (and honor) all three fields.

mongoose.Schema({
    companyName: {
        type: String,
        required: true
    },
    companyEmail: {
        type: String,
        required: true
    },
    companySite: {
        type: String,
        required: true
    }
});

Upvotes: 1

Nick
Nick

Reputation: 352

If you're using html form data, the fields will still get processed as an empty string "". On the backend, I would check if companyName.length > 0, and handle the error before inserting the data to mongodb

Upvotes: 1

Related Questions