简体   繁体   中英

MongoDB/Mongoose Query for multiple objects

I got an MongoDB database that consists from 3 collections.

  1. Categories
  2. Subcategories
  3. Products

Each product has the following 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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