node.js - Get all documents of a type in mongoose but only with 1 specific item of each documents array -


i'm using express 4 , mongoose rest api. have multiple documents of type "shop". each shop holds (besides other information) array called "inventory" holds again multiple items. each item has properties name , price.

now have api call can shops "cheapest" product item in json response. i'm totally stuck in creating query returns shops instead of including items of inventoryjust includes inventory item lowest price item in inventory array.

i found hints on how exclude fields using following query there whole array excluded:

shop.find({},  {inventory: 0},function(err, shops) {     if (err) {         res.send(err);     } else {         res.json(shops);     } }); 

update 1: schemas

// shop var shopschema = new schema({     name: { type: string, required: true},     address: {         street: string,         zipcode: number,         city: string     },     inventory: [inventoryitemschema] });  // inventoryitem var inventoryitemschema = new schema({     name: { type: string, required: true},     currentprice: {         amount: { type: number, required: true },         added: date     },     pastprices: [] }); 

update 2: came up

shop.find(function(err, shops) {     if (err) {         res.send(err);     } else {          shops.foreach(function(shop) {             // keep cheapest inventory item in array             var cheapestinventoryitem;             shop.inventory.reduce(function (previousitem, currentitem) {                 if (currentitem.currentprice.amount < previousitem.currentprice.amount) {                     cheapestinventoryitem = currentitem;                     return currentitem;                 } else {                     cheapestinventoryitem = previousitem;                     return previousitem;                 }             });             shop.inventory = [cheapestinventoryitem];         });          res.json(shops);     } }); 

mongodb find method returns document. in case array of shops fold fields anyway.

you can filter items js:

var cheapestitem; var cheapestprice = shop.inventory.items.reduce(function (lowest, item) {     if (item.price < lowest) {         cheapestitem = item;         return item.price;     } }, infinity); 

or can normalize schema , create collection items:

[{itemid: 1, shopid: 1, price: 100}] 

so query is:

db.item.group( {      key: { shopid: 1, itemid: 1, price: 1 },      reduce: function ( lowest, res ) { if (result.price < lowest) return result.price },      initial: infinity }) 

so must shopid , itemid lowest price


Comments

Popular posts from this blog

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -