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).
'express' 카테고리의 다른 글
body-parser[Middleware] (0) | 2020.07.03 |
---|---|
How to test passport-facebook /Social login test [TDD] (0) | 2020.06.28 |
Permission check on user's actions [Express, Node] (0) | 2020.05.21 |
When we forgot password/ using registered email. [Express, Node] (0) | 2020.05.21 |
Query mongoose (0) | 2020.05.21 |