Search code examples
expressmongoosemongoose-populate

Express Js + Mongoose + Joins


I have two collections. size and items. size is referred in items, I need to add size title while query items

Size collection

size:[{
_id: 123
title: S
},{
_id: 456
title:M
}]

Item collection

items:[{
title: item1,
    sizes:[{
     _id: object I'd
     sizeid: 123
     Price: 100
     },{
       _id: object I'd
       sizeid: 456,
       Price: 150
      }]
   }]

How to perform the join to get below output

items:[{
title: item1,
    sizes:[{
     _id: object I'd
     sizeid: 123
     size: S ----> from size collection
     Price: 100
     },{
       _id: object I'd
       sizeid: 456,
       size: M -----;> from size collection
       Price: 150
      }]
   }]

Solution

  • You need to design a property sizes of Items Schema as a array of ObjectIDs which will refer to Sizes Schema.

    const ItemSchema = new Schema(
      {
        ...
        sizes: [{ type: Schema.Types.ObjectId, ref: 'Sizes' }]
      }
    );
    
    

    Then when you need to get size just doing

    const result = await Items.findOne(_id: itemId).populate('sizes');