Course

Relationships and Referencing Models in Mongoose

In this lesson, we will learn how to reference models in Mongoose.

What is Referencing?

Referencing is a way to establish a relationship between two models in Mongoose. This is done by storing the _id of one model in another model.

For example, let's say we have two models:

and .

We can reference the model in the model by storing the _id of the in the model.

Why Use Referencing?

Referencing is useful when you want to establish a relationship between two models. This allows you to query related data easily and efficiently.

When designing your database schema, you should consider using referencing if the following apply:

  • You have at least two distinct models that you need to relate to one another
  • You need to query related data
  • You need to query the individual models separately

What does this mean? It means that if you have two models that are related to each other, you should consider using referencing to establish that relationship. For example with the and models, you may want to query all the books written by a specific author. By referencing the in the model, you can easily query this information.

Insight

If for some reason we never needed to query the books written by a specific author, we could consider embedding the documents in the document instead using an

embedded schema

instead.

What is a reference?

In mongoose, a reference is just another data type that you can use in your schema.

So just like you have a type of String, Number, Boolean, etc., you also have a type of ObjectId which is used to reference another model.

When you reference a model in another model, you are storing the of the referenced model in the referencing model.

Creating a Referenced Model

//
// Define the Author schema
const authorSchema = new mongoose.Schema({
  name: String,
  age: Number
});

// Create the Author model
const Author = mongoose.model('Author', authorSchema);

// Define the Book schema
const bookSchema = new mongoose.Schema({
title: String,
});

// Create the Book model
const Book = mongoose.model('Book', bookSchema);
//
const authorSchema = new mongoose.Schema({
  name: String,
  age: Number
});

const Author = mongoose.model('Author', authorSchema);

const bookSchema = new mongoose.Schema({
  title: String,
  // here we reference the 'author' model in our 'book' schema
  author: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Author'
  }
});

const Book = mongoose.model('Book', bookSchema);

Take note of the field in the . This field is of type and references the model.

Creating a Document with a Reference

When creating a document with a reference, you need to provide the _id of the referenced model.

//
// Create an Author document
const author = await Author.create({
  name: 'J.K. Rowling',
  age: 55
});

// Create a Book document with a reference to the Author
const book = await Book.create({
title: 'Harry Potter and the Philosopher\'s Stone',
// passing in the id from the previously created author creates a reference
author: author.\_id
});

In the example above, we first create an document and then create a document with a reference to the document.

Insight

You don't need to create the document before creating the document. You could have just queried the document by its name and used the _id to create the document.

Populating a Reference

When you query a document with a reference, the reference will be stored as an . If you want to get the actual document that the reference points to, you can use the method.

//
// Query the Book without populating the author
const book = await Book.findById('bookId');

console.log(book);
//
{
  _id: 'bookId',
  title: 'Harry Potter and the Philosopher\'s Stone',
  author: new ObjectId('authorId')
}

If you want to get the actual author document instead of just the _id, you can use the populate method, and pass in the name of the field you want to populate.


//
// Query the Book and populate the author
const book = await Book.findById('bookId').populate('author');

console.log(book);
//
{
  _id: 'bookId',
  title: 'Harry Potter and the Philosopher\'s Stone',
  author: {
    _id: 'authorId',
    name: 'J.K. Rowling',
    age: 55
  }
}

In the example above, we first query the document without populating the field. This will return the field as an .

This is what's known as a one to many relationship.

One author can have many books.

This is a common relationship in databases and is often used in applications that need to store data in a structured way.

In the next lesson, we will learn how to establish a many to many relationship between two models in Mongoose.

0 Comments

"Please login to view comments"

glass-bbok

Join the Conversation!

Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.

Upgrade your account
tick-guideNext Lesson

Many-To-Many References in Mongoose