MongoDB Schema using Mongoose

What to expect from this article?

  1. Simple JSON Object Schema.
  2. What is ObjectId?
  3. Multilevel JSON Object Schema
  4. Multilevel JSON Object with an attribute whose schema is not fixed
  5. Different configurations while defining a Schema
  6. Referential integrity in MongoDB Collections
  7. Use of Populate in Mongoose
  8. Attribute as Primary key or set of attributes as Primary key in a Collection

Simple JSON Schema

As you can see, if you want more control over the attribute, use an object while defining the schema of an attribute. Example: phone attribute is of type string and it is a required attribute. If you try to create a document without the phone, then mongoose will throw an error.

email: String is a shorthand notation if you just need to define the data type as String.

The permitted SchemaTypes are:

  • String, Number, Date, Boolean, Array, Decimal128
  • Buffer -> Used for storing binary data like images, word, txt or pdf files
  • ObjectId -> Used to refer documents of another collection
  • Map ->New in Mongoose 5.1.0

What is ObjectId?

An ObjectId is a special type typically used for unique identifiers.

ObjectId is a class. However, they are often represented as strings. When you convert an ObjectId to a string using toString(), you get a 24-character hexadecimal string:

While querying using Object id, make sure you convert string form of Object id to objectId type. Follow below example:

Different configurations while defining a Schema

Note: Some options work on certain types only

  • lowercase: boolean, whether to always call .toLowerCase() on the value
  • uppercase: boolean, whether to always call .toUpperCase() on the value
  • trim: boolean, whether to always call .trim() on the value
  • match: RegExp, creates a validator that checks if the value matches the given regular expression
  • enum: Array, creates a validator that checks if the value is in the given array.
  • minlength: Number, creates a validator that checks if the value length is not less than the given number
  • maxlength: Number, creates a validator that checks if the value length is not greater than the given number

Options that are available for all schemas:

  • required: boolean or function, if true adds a required validator for this property
  • default: Any or function, sets a default value for the path. If the value is a function, the return value of the function is used as the default.
  • select: boolean, specifies default projections for queries
  • validate: function, adds a validator function for this property
  • get: function, defines a custom getter for this property using Object.defineProperty().
  • set: function, defines a custom setter for this property using Object.defineProperty().
  • alias: string, mongoose >= 4.10.0 only. Defines a virtual with the given name that gets/sets this path.

Multilevel JSON Object Schema

Multilevel JSON Object with an attribute whose schema is not fixed

Referential integrity in MongoDB Collections

We can embed a child object within a parent object using the object id of the child.

As you can see in the above example, the parent has the id of child linked to it and therefore parent will always be linked to the latest form of child document. Now how to get the child document while querying the parent.

Use of Populate in Mongoose

Note: When there’s no document, parent.author will be null.If you have an array of authors in your parentSchema, populate() will give you an empty array instead.

Use chaining in populate for populating multiple child references.

Example: A User schema with friends attribute that stores objectIds of other users who are friends.

Populate lets you get a list of a user's friends, but what if you also wanted a user's friends of friends? Specify the populate option to tell mongoose to populate the friends array of all the user's friends:

Mongoose can also populate from multiple collections based on the value of a property in the document. Let’s say you’re building a schema for storing comments. A user may comment on either a blog post or a product.

The refPath option is a more sophisticated alternative to ref. If ref is just a string, Mongoose will always query the same model to find the populated subdocs. With refPath, you can configure what model Mongoose uses for each document.

Attribute as Primary key or set of attributes as Primary key in a Collection

Suffering from Knowledge Quest

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store