我的REST API使用的是Express 4和Mongoose。因此,我有多个“商店”类型的文档。每个商店(除其他信息外)都保存一个称为“库存”的数组,该数组又包含多个项目。每个项目本身都有名称和价格之类的属性。
现在,我希望有一个API调用,在这里我可以得到所有商店,但只能使用json响应中的“最便宜”产品项。但是我完全陷入了创建返回我所有商店的查询的麻烦,而不是包括库存中的所有项目,而是只将价格最低的库存项目作为库存数组中的唯一项目。
我发现了一些如何使用以下查询来排除字段的提示,但整个数组将被排除:
Shop.find({}, {inventory: 0},function(err, shops) {
if (err) {
res.send(err);
} else {
res.json(shops);
}
});
更新1:我的模式
// 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: []
});
更新2:这就是我的想法
Shop.find(function(err, shops) {
if (err) {
res.send(err);
} else {
shops.forEach(function(shop) {
// Only keep the currently cheapest inventory Item in the 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方法返回一个文档。因此,在您的情况下,无论如何将是拥有折叠场的商店。
您可以使用js过滤项目:
var cheapestItem;
var cheapestPrice = shop.inventory.items.reduce(function (lowest, item) {
if (item.price < lowest) {
cheapestItem = item;
return item.price;
}
}, Infinity);
或者,您可以规范化架构并创建集合项:
[{itemId: 1, shopId: 1, price: 100}]
因此查询为:
db.Item.group(
{
key: { shopId: 1, itemId: 1, price: 1 },
reduce: function ( lowest, res ) { if (result.price < lowest) return result.price },
initial: Infinity
})
因此,您必须以最低的价格获得shopId和itemId
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句