Matching product id from product collection to another invoice collection's products field which also array of product's selling date wise


#1

hii guys i am using meteor publication subscription method to display my data. i am having problem could you please help me with this.

i have one productMaster Collection , its an collection of product’s detail object like this

 [{
_id:1,
name:'mango',
price:30, 
},
{
_id:2,
name:'orange',
price:40, 
},
{
_id:3,
name:'banana',
price:50, 
}
,{
_id:4,
name:'apple',
price:60, 
}] 

And i have another invoice collecion which shows details of created invoice in perticular date with selected products with quantity like this.

[{
 _id:1
  products:[{_id:1,qty:5},{_id:2,qty:5},{_id:3,qty:5}]
 },
 {
 _id:2
 products:[{_id:1,qty:5},{_id:2,qty:5},{_id:3,qty:5}]
},
{
 _id:3
 products:[{_id:1,qty:5},{_id:2,qty:5},{_id:3,qty:5}]
}]

so i want to join two collection to know how many times i have sold my each and individual products , or you can say matching both product._id in both collection to filter it out.

note:if anyone suggest aggregation method of mongodb it is not working in meteor, meteor says invoice.aggreagte() is not a function


#2

I think this should do it :slight_smile:

Products.find().forEach(product => {
  let sum = 0
  Invoices.find({products:{$elemMatch:{_id:product._id}}}).forEach(invoice => {
    sum += invoice.products.find(p => p._id == product._id).qty
  })
  console.log(product.name, sum)  
})

#3

where should i write it client side or server side?