【问题标题】:I am having trouble calling a product from the database. (MongoDb - Nodejs)我无法从数据库中调用产品。 (MongoDb - Nodejs)
【发布时间】:2021-05-20 14:27:06
【问题描述】:

当我在搜索框中输入 phone 时,我在数据库中找到并获取了所有带有 phone 字样的类别。然后我想通过将这个类别的_id号与产品的类别id号匹配来找到产品。但我无法收集在单个数组中找到的产品。这就是为什么我不能将它们全部打印在屏幕上的原因。由于在数组中创建了两个不同的数组,因此它会打印第一个数组中的产品,但不会传递给第二个数组。

array in array

从图片中可以看出,我无法打印它,因为第三个产品在另一个数组中。

function escapeRegex(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
};

let model = [];
const searchRegex = new RegExp(escapeRegex(req.query.search), 'gi');
  SubSubCategory.find({ "name": searchRegex})
      .then(subsubcategoriesProduct => {
          subsubcategoriesProduct.forEach(p => {
              Product.find({ categories: p._id })
              .then(finalProduct => {
                  model.push(finalProduct);
                  res.render('shop/products', {
                      title: 'Tüm Ürünler',
                      products: model,
                      path: '/products',
                      searchRegex: searchRegex
                  });
...

【问题讨论】:

    标签: javascript node.js arrays mongodb backend


    【解决方案1】:

    如果subsubcategoriesProduct 中有 50 个产品,那么您将在 forEach 中一次启动 50 个新的 Mongo 查询。这些Product.find 操作中的每一个都是异步的,将在一段时间后完成,触发50 res.render。你不能那样做,你只能有一个res.render

    使用传统的.then() 语法处理这类事情很复杂,很容易导致回调地狱(然后是内部然后内部)。使用 await 而不是 .then() 让事情变得更容易。

    此外,您应该使用 _id 数组进行一次查询,而不是进行 50 个查询(每个 _id 一个)。

    const subcategories = await SubSubCategory.find({ name: searchRegex}, '_id')
                                            .lean() // return only JSON, not full Mongoose objects
                                            .exec(); // Returns a Promise so we can use await on it
    
    const ids = subcategories.map(s => s._id);
    
    const model = await Product.find({ categories: { $in : ids } }).lean().exec();
    
    res.render('shop/products', {
                    title: 'Tüm Ürünler',
                    products: model,
                    path: '/products',
                    searchRegex: searchRegex
                });
    

    【讨论】:

    • 非常感谢您提供的信息丰富的回答,它真的对我有用,我很感激。
    【解决方案2】:

    我这样解决了我的问题。

    function escapeRegex(text) {
        return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    };
    
    exports.getSearch = async (req, res, next) => {
        try{
            const subsubcategories = await SubSubCategory.find();
            const subcategories = await SubCategory.find();
            const categories = await Category.find();
            
            if(req.query.search){
                var searchRegex = new RegExp(escapeRegex(req.query.search), 'gi');
            }
    
            const subsubcategoriesProduct = await SubSubCategory.find({ "name": searchRegex}, '_id')
    
            const ids = subsubcategoriesProduct.map(s => s._id);
    
            const finalProduct = await Product.find({ categories: {$in: ids} });
    
            res.render('shop/products', {
                title: 'Tüm Ürünler',
                products: finalProduct,
                path: '/products',
                categories: categories,
                subcategories: subcategories,
                subsubcategories: subsubcategories,
                searchRegex: searchRegex,
                inputs:{
                    takeSecondHand: '',
                    takeMinPrice: '',
                    takeMaxPrice: ''
                }
            });
        }
        catch(err){
            next(err);
        }
    }

    【讨论】:

      猜你喜欢
      • 2013-01-08
      • 2018-09-30
      • 2017-11-28
      • 1970-01-01
      • 2020-04-29
      • 1970-01-01
      • 1970-01-01
      • 2018-04-26
      • 1970-01-01
      相关资源
      最近更新 更多