A Comprehensive Guide to MongoDB Schema Options and Parameters w/ examples.

A Comprehensive Guide to MongoDB Schema Options and Parameters w/ examples.

ยท

10 min read

Table of contents

No heading

No headings in the article.

Mongoose offers a wide range of options and parameters that allow you to customize the behavior of your schema to suit your needs. In this post, I'll go over all of the available options and parameters and explain how and when to use them.

๐Ÿ”น type: This option is used to specify the data type of the field. Mongoose supports several built-in types such as String, Number, Date, Boolean, Buffer, ObjectId, Decimal128, Map, Array, Mixed, Schema.Types.ObjectId, Schema.Types.Decimal128 and Schema.Types.Map. Each type has its own validation and behavior. For example, the String type will only accept string values, the Number type will only accept numeric values, and the Date type will only accept date values.

Here is a brief explanation of each type:

  • String: This type is used to represent string data. It can be used to store text, names, and any other data that can be represented as a string.

  • Number: This type is used to represent numeric data. It can be used to store numbers, counts, and any other data that can be represented as a number.

  • Date: This type is used to represent date and time data. It can be used to store dates, timestamps, and any other data that can be represented as a date.

  • Boolean: This type is used to represent Boolean data. It can be used to store true/false values, on/off values, and any other data that can be represented as a Boolean.

  • Buffer: This type is used to represent binary data. It can be used to store images, audio, and any other data that can be represented as a buffer.

  • ObjectId: This type is used to represent ObjectIds. ObjectId is a 12-byte BSON type, typically used as the primary key for a collection.

  • Decimal128: This type is used to represent decimal numbers. It can store numbers with a high precision and a wide range of values.

  • Map: This type is used to represent a Map data structure. It can store key-value pairs, similar to a JavaScript object.

  • Array: This type is used to represent an array of data. It can store multiple values of the same type.

  • Mixed: This type is used to represent any type of data. It is useful when the field can have any type of value and you don't want to specify a type.

  • Schema.Types.ObjectId: This type is used to represent ObjectIds. It works the same as the ObjectId type, but it is more explicit.

  • Schema.Types.Decimal128: This type is used to represent decimal numbers. It works the same as the Decimal128 type, but it is more explicit.

  • Schema.Types.Map: This type is used to represent a Map data structure. It works the same as the Map type, but it is more explicit.

  • Schema.Types.Array: This type is used to represent an Array data structure. It works the same as the Array type, but it is more explicit.

Usage:

const schema = new mongoose.Schema({
  name: { type: String },
  age: { type: Number }
});

๐Ÿ”น required: This option sets the field as required or not.

const schema = new mongoose.Schema({
  name: { type: String, required: true },
  age: { type: Number, required: true }
});

๐Ÿ”น unique: This option sets the field as unique or not.

const schema = new mongoose.Schema({
  email: { type: String, unique: true }
});

๐Ÿ”น default: This option sets a default value for the field.

const schema = new mongoose.Schema({
  name: { type: String, default: 'John Doe' }
});

๐Ÿ”น validate: This option validates the field using a custom validation function.

const schema = new mongoose.Schema({
  name: {
    type: String,
    validate: function(val) {
      return val.length > 5;
    }
  }
});

๐Ÿ”น get: This option allows you to define a getter function that will be called when you access the field's value. This is useful for transforming the value before it is returned to the user. For example, you might use a getter to convert a field's value to uppercase before it is returned.

const schema = new mongoose.Schema({
  name: {
    type: String,
    get: function(val) {
      return val.toUpperCase();
    }
  }
});

๐Ÿ”น set: This option allows you to define a setter function that will be called when you set the field's value. This is useful for transforming the value before it is saved to the database. For example, you might use a setter to convert a field's value to lowercase before it is saved.

const schema = new mongoose.Schema({
  name: {
    type: String,
    set: function(val) {
      return val.toLowerCase();
    }
  }
});

๐Ÿ”น index: This option allows you to create an index for the field. Indexing a field can improve the performance of queries that use that field. It is important to note that adding indexes can also slow down writes to the database, so use them judiciously.

const schema = new mongoose.Schema({
  name: { type: String, index: true }
});

๐Ÿ”น select: This option specifies if the field should be selected or not by default.

const schema = new mongoose.Schema({
  name: { type: String, select: false }
});

๐Ÿ”น enum: This option specifies a list of allowed values for the field.

const schema = new mongoose.Schema({
  color: { type: String, enum: ['red', 'green', 'blue'] }
});

๐Ÿ”น sparse: This option is used in combination with the index option. When sparse is set to true, MongoDB will only index documents that have the indexed field. This is useful when you have a large collection and not all documents have the indexed field.

const schema = new mongoose.Schema({
  age: { type: Number, sparse: true }
});

๐Ÿ”น ref: This option specifies a reference to another model.

const userSchema = new mongoose.Schema({
  name: { type: String }
});
const postSchema = new mongoose.Schema({
  title: { type: String },
  author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
});

๐Ÿ”น autopopulate: This option allows you to automatically populate a field with the referenced documents when querying. This is useful when you need to access the referenced

const userSchema = new mongoose.Schema({
  name: { type: String }
});
const postSchema = new mongoose.Schema({
  title: { type: String },
  author: { type: mongoose.Schema.Types.ObjectId, ref: 'User', autopopulate: true }
});

๐Ÿ”น min: This option specifies the minimum value (works with Number, Date, String and Array fields)

const schema = new mongoose.Schema({
  age: { type: Number, min: 0 }
});

๐Ÿ”น max: This option specifies the maximum value (works with Number, Date, String and Array fields)

const schema = new mongoose.Schema({
  age: { type: Number, max: 100 }
});

๐Ÿ”น minlength: This option specifies the minimum length (works with String and Array fields)

const schema = new mongoose.Schema({
  name: { type: String, minlength: 5 }
});

๐Ÿ”น maxlength: This option specifies the maximum length (works with String and Array fields)

const schema = new mongoose.Schema({
  name: { type: String, maxlength: 10 }
});

๐Ÿ”น match: This option specifies the regex pattern that the field should match (works with String fields)

const schema = new mongoose.Schema({
  email: { type: String, match: /[a-z]/ }
});

๐Ÿ”น trim: This option specifies if the leading and trailing white spaces should be trimmed (works with String fields)

const schema = new mongoose.Schema({
  name: { type: String, trim: true }
});

๐Ÿ”น lowercase: This option specifies if the field should be automatically converted to lowercase (works with String fields)

const schema = new mongoose.Schema({
  name: { type: String, lowercase: true }
});

๐Ÿ”น uppercase: This option specifies if the field should be automatically converted to uppercase (works with String fields)

const schema = new mongoose.Schema({
  name: { type: String, uppercase: true }
});

๐Ÿ”น versionKey: This option allows you to specify the name of the version key field that Mongoose will use to track versions of a document. By default, Mongoose uses "__v" as the version key. When you set the versionKey option, Mongoose will use the specified field name instead.

const schema = new mongoose.Schema({
  name: { type: String },
}, { versionKey: '_version' });

๐Ÿ”น timestamps: This option automatically adds createdAt and updatedAt timestamps to the documents.

const schema = new mongoose.Schema({
  name: { type: String },
}, { timestamps: true });

๐Ÿ”น toJSON: This option allows you to configure the behavior of the built-in toJSON() method, which is used to convert a Mongoose document to a plain JavaScript object. You can use this option to include or exclude virtuals, getters, and other properties from the resulting object. For example, you might use this option to include virtuals in the object so that they can be easily accessed on the client side.

const schema = new mongoose.Schema({
  name: { type: String },
}, { toJSON: { virtuals: true } });

๐Ÿ”น toObject: This option allows you to configure the behavior of the built-in toObject() method, which is used to convert a Mongoose document to a plain JavaScript object. This option is similar to the toJSON option, but it applies to the toObject() method instead.

const schema = new mongoose.Schema({
  name: { type: String },
}, { toObject: { virtuals: true } });

๐Ÿ”น id: This option allows you to specify if the id field should be added to the schema or not. By default, Mongoose will add an id field to the schema and automatically generate an ObjectId for each document. When id: false is set, Mongoose will not add an id field to the schema. This can be useful if you want to use a different field as the primary key or if you want to manually set the id field.

const schema = new mongoose.Schema({
  name: { type: String },
}, { id: false });

๐Ÿ”น _id: This option allows you to configure the _id field. You can use this option to specify the type of the _id field, set a default value, or enable/disable automatic generation of the _id field. This is useful if you want to use a different type for the _id field than the default ObjectId, or if you want to set a custom _id value for each document.

const schema = new mongoose.Schema({
  name: { type: String },
}, { _id: false });

๐Ÿ”น _id: This option allows you to enable automatic generation of the _id field. This is useful when you want Mongoose to automatically generate a unique value for the _id field, for example, using a library like shortid.

const schema = new mongoose.Schema({
  _id: { type: String, default: shortid.generate }
});

๐Ÿ”น _id: This option allows you to enable automatic generation of the _id field. This is useful when you want Mongoose to automatically generate a unique value for the _id field, for example, using a library like mongoose-autopopulate.

const schema = new mongoose.Schema({
  _id: { auto: true }
});

๐Ÿ”น noId: This option specifies if the _id field should be added to the schema (defaults to true)

const schema = new mongoose.Schema({
  name: { type: String },
}, { noId: true });

๐Ÿ”น strict: This option allows you to enable or disable strict mode for the schema. By default, Mongoose uses strict mode, which means that any new or modified fields that are not part of the schema will be ignored. When strict mode is disabled, Mongoose will automatically add new fields to the schema and allow you to save them. This can be useful in situations where you want to allow for dynamic data without having to manually update the schema. However, be aware that disabling strict mode can make it more difficult to maintain data integrity and consistency.

const schema = new mongoose.Schema({
  name: { type: String },
}, { strict: false });

๐Ÿ”น selectPopulatedPaths: This option allows you to specify if the populated paths should be selected or not by default. When this option is set to true, Mongoose will automatically select the populated paths when querying. This can be useful when you want to always include the populated documents in the returned result. When this option is set to false, you will need to explicitly select the populated paths using the .select() method.

const schema = new mongoose.Schema({
  name: { type: String },
}, { selectPopulatedPaths: true
ย