Add/Merge element from from one Object to another Object inside array
If I understand correctly, the aim is to create a new collection of aucs
like the ones found, each updated to include an item name from the item
collection where the item has a matching id.
let aucs = [ { _id: "5c00faa4936359120ceb3632", auc: 177215422, item: 130251, price: 26000000, lastModified: 1543567955000, date: "2018-11-30T08:53:56.290Z", __v: 0 }, { _id: "5c00faa4936359120ceb363f", auc: 177215440, item: 130251, price: 26000000, lastModified: 1543567955000, date: "2018-11-30T08:53:56.290Z", __v: 0 } ]; item = [ { _id: "5bcd8a6134cdd1223cd3239b", id: 130251, name: 'TEST_NAME_1', __v: 0 }, { _id: "5bcd8a6134cdd1223cd3239b", id: 130252, name: 'TEST_NAME_2', __v: 0 }]; // create a new collection of aucs modified to include the names of matching itemslet combined = [];aucs.forEach(auc => { let combinedAuc = Object.assign({}, auc); combined.push(combinedAuc); let matchingItem = item.find(i => auc.item === i.id); if (matchingItem) combinedAuc.name = matchingItem.name});console.log(combined)
Would be more superior and faster if you use some aggregation trick here
auctions.aggregate([ { "$match": { "owner": "owner", "place": "place" }}, { "$lookup": { "from": "items", "let": { "item": "$item" }, "pipeline": [ { "$match": { "$expr": { "$eq": ["$id", "$$item"] }}} ], "as": "item" }}, { "$limit": 15 }])