简体   繁体   English

MongoDB/Mongoose 查询多个对象

[英]MongoDB/Mongoose Query for multiple objects

I got an MongoDB database that consists from 3 collections.我有一个 MongoDB 数据库,它由 3 个 collections 组成。

  1. Categories类别
  2. Subcategories子类别
  3. Products产品

Each product has the following model:每个产品都有以下model:

const ProductSchema = new Schema({
    category: String,
    subcategory: String,
    name: String,
    description: String,
    price: String,
    Image: [{
        url: String,
        filename: String
    }],
    deleteImages: []  

});

What I want is to query a category then get the subcategories that belong to the category and (here is the question:) from the found subcategories query the products that belong to them.我想要的是查询一个类别,然后获取属于该类别的子类别,并且(这里是问题:)从找到的子类别中查询属于它们的产品。

app.get("/api/front/show/:category", asyncHandler(async(req,res)=>{
  const category = req.params.category;
  const subcategories = await SubCategoryMd.find({'category' : category});
  const products = await ProductMd.find({/* Pass here the found subcategories */});
  res.json({subcategories, products});
}));

How do I query multiple objects with find?如何使用 find 查询多个对象?

app.get("/api/front/show/:category", asyncHandler(async(req,res)=>{
  let products = []
  const category = req.params.category;
  const subcategories = await SubCategoryMd.find({'category' : category});
  const productsBulk = await ProductMd.find({}).collation({ locale: 'el' }).sort('name');
  productsBulk.forEach(product => {
    subcategories.forEach(subcategory => {
      if(subcategory.name === product.subcategory){
        products.push(product)
      }
    });
  });
  res.json({subcategories, products});
}));

This is a simple solution but it already pulls all the products and on top of that it is a very expensive function to run in my opinion.这是一个简单的解决方案,但它已经提取了所有产品,除此之外,我认为它是一个非常昂贵的 function 运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM