Monday, 3 April 2017

$lookup populate all data from other collection

I have 2 collections product and category problem is when I use $lookup it will populate each product with all categories but not just with categories inside product model:

product schema:

cats: [{
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Category'
        }],

here is the query part:

Product.aggregate([
            {"$lookup": {
                    "from": "categories",
                    "localField": "products.cats",
                    "foreignField": "categories._id",
                    "as": "cat"
                }},
            {$project: {
                    "cat": "$cat",
                    name: 1,
                    category: 1
                }}
        ]

Anyone know what is a poroblem?



via Vladimir Djukic

No comments:

Post a Comment