[英]I am having trouble calling a product from the database. (MongoDb - Nodejs)
当我在搜索框中输入 phone 时,我在数据库中找到并获取了所有带有单词 phone 的类别。 然后我想通过将这个类别的_id号与产品的类别id号匹配来找到产品。 但我无法收集在单个数组中找到的产品。 这就是为什么我不能将它们全部打印在屏幕上的原因。 Since two different arrays are created in the arrays, it prints the products in the first arrays, but does not pass to the second arrays.
从图片中可以看出,我无法打印它,因为第三个产品在另一个数组中。
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()
语法处理这类事情很复杂,很容易导致回调地狱(然后在里面然后在里面)。 使用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); } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.