Preview:
Building Relationships
In the past, NoSQL entailed a completely non-relational approach to database creation. Over time, though, non-relational databases began to incorporate some of the strengths of the relational approach. One of these strengths is building relationships. In this lesson, we will learn how to set up relationships between models in MongoDB.

1. Building a Relationship Between Two Schemas
Building a relationship begins with a schema. 

Imagine an app that has two entities: users and ads. The user schema looks like this:

const userSchema = new mongoose.Schema({
  name: { // the user only has a name
    type: String,
    minlength: 2,
    maxlength: 20,
    required: true,
  },
});

module.exports = mongoose.model('user', userSchema);
 Save
Users can create ads that are defined by a title and a text field:

const adSchema = new mongoose.Schema({
  title: {
    type: String,
    minlength: 2,
    maxlength: 20,
    required: true,
  },
  text: {
    type: String,
    minlength: 2,
    required: true,
  },
});

module.exports = mongoose.model('ad', adSchema);
 Save
Now we'll need a way to assign an author to each advertisement. Let's make another field titled 'creator'. This field will store a link to the ad author.

An identifier is the best way to set up a relationship between documents. MongoDB automatically creates the _id field, which provides a unique identifier for each document and allows documents to be linked to one another.

To do this with schemas, the type property should be set to mongoose.Schema.Types.ObjectId. It should also have a ref property, which will contain the name of the model we are linking:

const adSchema = new mongoose.Schema({
  title: {
    type: String,
    minlength: 2,
    maxlength: 20,
    required: true,
  },
  text: {
    type: String,
    minlength: 2,
    required: true,
  },
  // add the creator field
  creator: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'user',
    required: true
  },
});
 Save
2. Including the _id Field During Document Creation
In the previous step, we created a model and specified that there should be a customer document identifier in the creator field. Now we need to make sure this identifier is recorded in the creator field whenever a new ad is created:

// controllers/ads.js

const Ad = require('../models/ad');

module.exports.createAd = (req, res) => {
  const { title, text, creatorId } = req.body;

  Ad.create({ title, text, creator: creatorId })
    .then(ad => res.send({ data: ad }));
};
 Save
3. Acquiring Complete Information via the populate() Method
The two models are now linked. However, the ad schema only stores the user ID. To get all  information about the author of the ad, you'll need to use the populate() method by passing it the field name:

// controllers/ads.js

const Ad = require('../models/ad');

module.exports.getAds = (req, res) => {
  Ad.find({})
    .populate('creator')
    .then(ad => res.send({ data: ad }));
};
 Save
In order to send a response containing the multiple fields resulting from the relationships, we need to pass an array to the populate() method:

// controllers/ads.js

const Ad = require('../models/ad');

module.exports.getAds = (req, res) => {
  Ad.find({})
    .populate(['creator', 'followers'])
    .then(ad => res.send({ data: ad }));
};
 Save
Links
Find out more about relationships in this mongoose guide:

https://mongoosejs.com/docs/populate.html
downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter