【问题标题】:MongoDB/Mongoose Query for multiple objectsMongoDB/Mongoose 查询多个对象
【发布时间】:2022-01-24 04:31:10
【问题描述】:

我有一个由 3 个集合组成的 MongoDB 数据库。

  1. 类别
  2. 子类别
  3. 产品

每款产品都有以下型号:

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

});

我想要的是查询一个类别,然后获取属于该类别的子类别,并且(这里是问题:)从找到的子类别中查询属于它们的产品。

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});
}));

如何使用 find 查询多个对象?

【问题讨论】:

    标签: node.js mongodb express mongoose mern


    【解决方案1】:
    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});
    }));
    

    这是一个简单的解决方案,但它已经提取了所有产品,此外,在我看来,这是一个非常昂贵的功能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-13
      • 2020-03-14
      • 2020-10-30
      • 2019-03-20
      • 1970-01-01
      • 2014-10-10
      • 2012-11-14
      • 1970-01-01
      相关资源
      最近更新 更多