11

Say I have a javascript object (the data) and I want to check to see if it conforms to a given Schema that I've defined.

Is there a way to do this without turning the schema into a model, creating an instance of that model populated with the data, and running mymodel.validate()?

I'd love to have a Schema(definition).validate(data, callback), but the validate function is defined on the Document class, from what I could tell.

Syntle
  • 5,168
  • 3
  • 13
  • 34
Jared Forsyth
  • 12,808
  • 7
  • 45
  • 54

3 Answers3

1

2021 update

Mongoose added that functionality as Model.validate(...) back in 2019 (v5.8.0):

You can:

try {
  await Model.validate({ name: 'Hafez', age: 26 });
} catch (err) {
  err instanceof mongoose.Error.ValidationError; // true
}
Hafez
  • 1,320
  • 2
  • 13
  • 24
0

One way is to perform that with the help of custom validators. When the validation declined, it failed to save the document into the database.

Or another way to do that through validate() function provided by MongoDB with the same schema as you defined.

Nafeo Alam
  • 4,000
  • 3
  • 14
  • 22
0

You can validate your schema on the Mongo side link
For example:

db.createCollection("students", {
   validator: {
      $jsonSchema: {
         bsonType: "object",
         required: [ "name" ],
         properties: {
            name: {
               bsonType: "string",
               description: "must be a string and is required"
            },
            year: {
               bsonType: "int",
               minimum: 2017,
               maximum: 3017,
               description: "must be an integer in [ 2017, 3017 ] and is required"
            }
         }
      }
   }
})
Ofir Bi
  • 236
  • 1
  • 2
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/29861893) –  Sep 19 '21 at 01:45