본문 바로가기

express

How to show joined models [mongoose]

MongoDB doesn't have "join". Instead join, mongoose Uses "virtaul" and "populate"

 

First, take a look at models.

ProductSchema

// app/model/product.js
const ProductSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      maxlength: 50
    },
    description: {
      type: String,
      maxlength: 1000
    },
    {
      toJSON: { virtuals: true },
      toObject: { virtuals: true },
    }
  });
  
// Reverse populate with virtuals
ProductSchema.virtual('Reviews', {   !!
  ref: 'Review',  // the model to use
  localField: '_id',  // Find review where '_id'
  foreignField: 'product', 
});
 
 module.exports = mongoose.model('Product', ProductSchema);

ReviewSchema

// app/models/review.js
const ReviewSchema = new mongoose.Schema({
  title: {
    type: String,
    maxlength: 100
  },
  content: {
    type: String,
    maxlength: 1000
  },
  product: {
    type: mongoose.Schema.ObjectId,
    ref: 'Product',
    required: true
  }
});

For example, When we need to show product document with related reviews. we usually use "populate()" method to populate review document. Probably we gonna use getProduct() method(which is pre defined). At getProduct method, we should put populate() method directly like below.

exports.getProduct = function() {
  ~~
  result = Product.find().populate(review); // Here  
  ~~
};

If we call getProduct method, we can get Product document with Reviews (which has this.Product_id).