Mongoose – Modeling Relationships Between Connected Data

Mongoose Node

Referencing Documents

// Customer Model
const Customer = mongoose.model(
  'Customer',
  new mongoose.Schema({
    name: String
  })
)

// Review Model
const Review = mongoose.model(
  'Review',
  new mongoose.Schema({
    rating: { type: Number, required: true },
    customer: {
      // this tells MongoDB to store the ObjectID() for later reference
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Customer' // references the Customer Model 
    }
  })
)

When you query the Review documents, it will return a reference to the Customer collection, but by default, customer only returns the ObjectId().

To get the customer data, we need to use the populate() method to replace the specified path in the document with the data from another document when running our query.

const reviews = await Review.find().populate('customer')

So in the above example, we are telling Mongoose to replace the customer path (which contains an ObjectId for reference) with the data from the Customer collection.

The second parameter of populate() is a list of properties you want to include. So if you only wanted the name, then your method would be.

Note: Mongoose uses a space seperated list for references.

const reviews = await Review.find().populate('customer', 'name')

To exclude a property, like ID. You can pass a negative reference.

const reviews = await Review.find().populate('customer', 'name -_id')

Embedding Documents

In order to embed a document into another, you will need assign the schema to a const in order to reference it.

// Customer Schema
const customerSchema = new mongoose.Schema({
  name: String
});

// Customer Model
const Customer = mongoose.model('Customer', customerSchema)

// Review Model
const Review = mongoose.model(
  'Review',
  new mongoose.Schema({
    rating: { type: Number, required: true },
    customer: { type: customerSchema, required: true }
  })
)

When you create a new record in the database, it will instead embed the customer document inside the review document.

Matthew Horne

Matthew is a web developer from the United Kingdom who taught himself PHP and JavaScript and never looked back. If you would like to hire me, shoot me an email.

No comments yet. Be the first.

Leave a Comment