Search code examples
node.jsmongoosemongoose-schema

Mongoose gives validation error even when required fields are present


I'm using the mongoose ODM for a project. My schema looks like this:

const applicantSchema = new Schema({
  regno: {
  type: String,
  unique: true,
  required: true
  },
  email: {
  type: String,
  unique: true,
  required: true
  }
});

const Applicant = mongoose.model('Applicant', applicantSchema);

I created a wrapper function to add a new document which looks like this:

function addApplicant(newApplicant, callback){
  mongoose.connect(url);

  const db = mongoose.connection;

  console.log(newApplicant);
  console.log(typeof newApplicant);

  const applicant = new Applicant(newApplicant);

  applicant.save((err) => {
    if(err) return callback(err);
    let info = "successfully saved target"; 
    return callback(null, info);
  });
}

I call this function within my route that handles the concerned post request.

router.post('/applicant/response', (req, res) => {
  //process sent response here and add to DB
  //console.log(req.body);
  let newApplicant = {
    regno: req.body.regno,
    email: req.body.email
  }
  //console.log(newApplicant);

  applicant.addApplicant(newApplicant, (err, info) => {
    if(err){ console.log(err); res.end(err);}
    res.end('complete, resp: ' + info);
  });
});

However, mongoose gives me a validation error (path 'regno' is required) even though I am supplying a value for regno. This happens with all the fields marked as required.

If I remove the 'required: true' option the document is saved to the db as expected.

Any help will be appreciated. :)


Solution

  • It turns out that in this case, something was wrong with the way postman was sending data in a POST request. When I tested this later in postman using JSON as the data format (and ensuring that the Content-Type header is set to application/json), the code worked as expected.

    To those facing a similar issue, check the headers postman sends with the request, and ensure that they are what you'd expect them to be.