【发布时间】:2015-01-26 02:21:04
【问题描述】:
我将 Express 4 和 Mongoose 用于我的 REST API。所以我有多个“商店”类型的文件。每个商店都持有(除其他信息外)一个称为“库存”的数组,该数组再次保存多个商品。每个项目本身都有名称和价格等属性。
现在我想要一个 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);
}
});
【问题讨论】:
标签: node.js mongodb express mongoose