我无法从数据库调用产品。 (MongoDb - 节点)

I am having trouble calling a product from the database. (MongoDb - Nodejs)

当我在搜索框中键入 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
                  });
...

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

使用传统的 .then() 语法处理这类事情很复杂,很容易导致回调地狱(then inside then inside 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
            });

我这样解决了我的问题。

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