K41F4r
K41F4r

Reputation: 1551

Mongoose schema optional with validation

Given a Schema like this:

new Schema(
    {
      someData: {
        someString: {
          required: false,
          maxlength: 400,
          type: String
        }
        otherData: {
          required: true,
          type: String
        }
});

someString is optional but has a validation to check if it's length is below 400.

If I'm given an invalid length string (>400) would this object still be saved but without the someString or would this throw an error? If this throws an error how can I change the schema so that the object will still get saved?

Upvotes: 0

Views: 579

Answers (1)

SuleymanSah
SuleymanSah

Reputation: 17888

It will throw an error without saving the document.

Let's say we have this schema:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const studentSchema = new Schema({
  someData: {
    someString: {
      required: false,
      maxlength: 5,
      type: String
    },
    otherData: {
      required: true,
      type: String
    }
  }
});

module.exports = mongoose.model("Student", studentSchema);

And this post route:

const Student = require("../models/student");

router.post("/students", async (req, res) => {
  try {
    const result = await Student.create(req.body);
    res.send(result);
  } catch (err) {
    console.log(err);

    if (err.name === "ValidationError") {
      return res.status(400).send(err.errors);
    }
    res.status(500).send("Something went wrong");
  }
});

When we send a bad request it will give ValidationError where we can read the error details from err.errors.

Request Body:

{
  "someData": {
    "someString": "123456",
    "otherData": "other"
  }
}

The response will be:

{
    "someData.someString": {
        "message": "Path `someData.someString` (`123456`) is longer than the maximum allowed length (5).",
        "name": "ValidatorError",
        "properties": {
            "message": "Path `someData.someString` (`123456`) is longer than the maximum allowed length (5).",
            "type": "maxlength",
            "maxlength": 5,
            "path": "someData.someString",
            "value": "123456"
        },
        "kind": "maxlength",
        "path": "someData.someString",
        "value": "123456"
    }
}

You can resolve this by removing the maxlength option, or check the field's length in your route, and if it's length is bigger than the specified maxlength, you can substr it so that it doesn't result in error.

router.post("/students", async (req, res) => {
  try {
    let doc = req.body;

    if (doc.someData && doc.someData.someString && doc.someData.someString.length > 5) {
      doc.someData.someString = doc.someData.someString.substring(0, 5);
    }

    const result = await Student.create(doc);
    res.send(result);
  } catch (err) {
    console.log(err);

    if (err.name === "ValidationError") {
      return res.status(400).send(err.errors);
    }
    res.status(500).send("Something went wrong");
  }
});

Upvotes: 1

Related Questions