MongoDB – Does Pure MongoDB Use Schemas and Models Like Mongoose?

mongodbnode.js

I'm new on pure MongoDB and I've some questions about pure MongoDB.


1. Does pure MongoDB use schemas and models like Mongoose ODM?

If you have used Mongoose ODM, you know that Mongoose ODM uses schemas and models for defining fields with their properties. Like this;

/* Dependencies */
const mongoose = require('mongoose');

/* Define the user schema */
const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  lastname: {
    type: String,
    required: true
  }
});

/* Define the model */
const User = mongoose.model('User', userSchema);

Do we need to define schemas and models with their fields?

2. Does pure MongoDB have any validators?

For example, If we have a field in schema; we can define some properties to fields like;

...
  name: {
    type: String,  // Type built-in validator
    required: true // Required built-in validator
  },
  points: {
    type: Number,  // Type built-in validator
    min: 0,        // Min (minimum) built-in validator
    max: 100       // Max (maximum) built-in validator
  },
  verified: {
    type: Boolean, // Type built-in validator
    validate: {    // Custom schema validator
      validator: function(v) {
        return this.points > 50;
      },
      message: 'You can not register!'
    }
  }
...

Does pure MongoDB support for any validators or we define them while CRUD operations like this;

function createUser(userData, db, callback) {
  if(userData.name && typeof(userData.name) == 'string' && userData.username && typeof(userData.lastname) == 'string') { // Validator for object
    const collection = db.collection('users');
    collection.insertOne({
      name: userData.name,
      lastname: userData.lastname
    }, function(err, result) {
      if(err) callback(err, null);
      console.log('One record writed!');
      callback(null, result);
    });
  } else {
    callback(new Error('You must enter name and lastname to register!', null));
  }
}

All my questions are about these. Thanks…

Best Answer

MongoDB supports schema validation.

As per MongoDB official documentation for Schema Vaidation.

MongoDB provides the capability to perform schema validation during updates and insertions.

You can specify the rules when creating a collection or add validation to existing documents as well with validator option.

Example from MongoDB documentation.

db.createCollection("students", {
   validator: {
      $jsonSchema: {
         bsonType: "object",
         required: [ "name", "year", "major", "gpa", "address.city", "address.street" ],
         properties: {
            name: {
               bsonType: "string",
               description: "must be a string and is required"
            },
            gender: {
               bsonType: "string",
               description: "must be a string and is not required"
            },
            year: {
               bsonType: "int",
               minimum: 2017,
               maximum: 3017,
               exclusiveMaximum: false,
               description: "must be an integer in [ 2017, 3017 ] and is required"
            },
            major: {
               enum: [ "Math", "English", "Computer Science", "History", null ],
               description: "can only be one of the enum values and is required"
            },
            gpa: {
               bsonType: [ "double" ],
               minimum: 0,
               description: "must be a double and is required"
            },
            "address.city" : {
               bsonType: "string",
               description: "must be a string and is required"
            },
            "address.street" : {
               bsonType: "string",
               description: "must be a string and is required"
            }
         }
      }
   }
})