当我在搜索框中输入phone时,我找到并获取了数据库中包含phone一词的所有类别。然后,我想通过将此类别的_id编号与产品的类别id编号进行匹配来查找产品。但是我不能在单个数组中收集我找到的产品。这就是为什么我不能把它们全部打印在屏幕上。因为在数组中创建了两个不同的数组,所以它打印第一个数组中的乘积,但不会传递给第二个数组。
正如你从图片中看到的,我不能打印它,因为第三个产品在另一个阵列中。
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
});
...
发布于 2021-05-20 14:47:03
如果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
});
发布于 2021-05-21 07:37:45
我用这种方式解决了我的问题。
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);
}
}
https://stackoverflow.com/questions/67622364
复制相似问题