Node.js 获取mongoose中同一类型的所有文档,但每个文档数组仅包含一个特定项
我正在使用Express4和Mongoose作为RESTAPI。所以我有多个“shop”类型的文档。每个商店(除其他信息外)都保存一个名为“库存”的数组,该数组再次保存多个项目。每个项目本身都有名称和价格等属性 现在,我希望有一个API调用,在这里我可以得到所有的商店,但只能在json响应中使用他们“最便宜”的产品项。但是我完全被困在创建这个查询中,它返回我的所有店铺,而不是包括库存的所有项目,而是将价格最低的库存项目作为库存数组中的唯一项目 我发现了一些关于如何使用以下查询排除字段的提示,但整个数组将被排除在外:Node.js 获取mongoose中同一类型的所有文档,但每个文档数组仅包含一个特定项,node.js,mongodb,express,mongoose,Node.js,Mongodb,Express,Mongoose,我正在使用Express4和Mongoose作为RESTAPI。所以我有多个“shop”类型的文档。每个商店(除其他信息外)都保存一个名为“库存”的数组,该数组再次保存多个项目。每个项目本身都有名称和价格等属性 现在,我希望有一个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);
}
});
Shop.find(函数(err,shops){
如果(错误){
res.send(err);
}否则{
商店。forEach(功能(商店){
//仅保留阵列中当前最便宜的库存项目
var CheapestInventory项目;
shop.inventory.reduce(函数(上一个项目,当前项目){
if(currentItem.currentPrice.amount
Mongodb find方法返回一个文档。因此,在你的例子中,它将是一系列的商店和他们的折叠场
您可以使用js筛选项目:
var cheapestItem;
var cheapestPrice = shop.inventory.items.reduce(function (lowest, item) {
if (item.price < lowest) {
cheapestItem = item;
return item.price;
}
}, Infinity);
因此,问题是:
db.Item.group(
{
key: { shopId: 1, itemId: 1, price: 1 },
reduce: function ( lowest, res ) { if (result.price < lowest) return result.price },
initial: Infinity
})
db.Item.group(
{
关键字:{shopId:1,itemId:1,price:1},
reduce:function(lowest,res){if(result.price
所以你必须以最低的价格获得shopId和itemId,很抱歉,我仍然没有得到这个。。。我刚刚用我的模式更新了我的原始帖子。“规范化你的模式”是什么意思?很好,我的意思是一样的。您只需将shopId添加到InventoryItem并使用mongo分组即可。如果它适合你的业务逻辑,我想我是一个大的noob得到正确的方式。然而,多亏了你对reduce函数的提示,我成功地得到了我想要的(见我原来的帖子)。大多数情况下肯定不是最好的方法,但它是有效的。所以非常感谢!
db.Item.group(
{
key: { shopId: 1, itemId: 1, price: 1 },
reduce: function ( lowest, res ) { if (result.price < lowest) return result.price },
initial: Infinity
})