MongoDB — Data Models
Understanding how to use MongoDB requires you to change the way you think about databases if you’re coming from a traditional relational database. A relational database structures data into tables and rows, while MongoDB structures data into collections of JSON documents.
Let’s look at a database example using the traditional author and books relationship.
Our authors will have a name, age, and books. Our books will have a title, rating, and genre.
Typically, the way this would be set up in a relational database is to have 2 tables. An authors table with a name and an age and a books table with the title, genre, rating, and an author ID so that you can find the author.
With MongoDB, you don’t need to do that. We can just create one collection and our related collection can be nested inside this collection.
So we have a list of authors. Each author ID has information about that author, such as a name, age and a list of books. The books key would point to an array. Each book that is nested inside the array has its own information. So each book ID would have a title, genre, and rating. All this data is nested directly within the author.
The JSON object of this collection looks something like this:
{
name: 'Mark Twain',
age: 74,
books: [
{ title: 'The Adventures of Huckleberry Finn', rating: 5, 'Fiction' },
{ title: 'Life on the Mississippi', rating: 4, genre: 'Biography' }
]
}The author has a structure and each book has a structure. So we will make 2 schemas. 1 for the authors and 1 for the books. It will be just one model but it will encompass 2 schemas.
Let’s create this new author model.
In models create a new file and call it author.js.
In author.js:
//Import mongoose and Schema
const mongoose = require(‘mongoose’)
const Schema = mongoose.Schema//Create Schema for author
const AuthorSchema = new Schema({
name: String,
age: Number,
books: []
})
The name field will be a string, age will be number, and books will be an array but we won’t start creating objects inside the array to show the book schema. Instead, we will create a new schema for books.
//Create Schema for book
const BookSchema = new Schema({
title: String,
rating: Number,
genre: String
})Now that we have a schema for the books, we can include that into the author schema inside the books field so that it knows that its an array of book schema objects. We are nesting one schema inside another.
const AuthorSchema = new Schema({
name: String,
age: Number,
books: [BookSchema]
})Now that we have our schemas we can create the actual model.
const Author = mongoose.model(‘author’, AuthorSchema)Mongoose will pluralize the name given when it comes to creating a collection. So the author collection would be called ‘authors’ and it will base it off the AuthorSchema. The last step is to export it.
Module.exports = Author