简体   繁体   English

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

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

When I typed phone in the search box, I found and fetched all categories with the word phone in the database.当我在搜索框中输入 phone 时,我在数据库中找到并获取了所有带有单词 phone 的类别。 Then I wanted to find the products by matching the _id number of this category with the category id number of the product.然后我想通过将这个类别的_id号与产品的类别id号匹配来找到产品。 but I cannot collect the products I find in a single array.但我无法收集在单个数组中找到的产品。 that's why I can't print them all on the screen.这就是为什么我不能将它们全部打印在屏幕上的原因。 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. 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.

array in array数组中的数组

As you can see from the picture, I cannot print it because the 3rd product is in the other 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 }); ...

If there are 50 products in subsubcategoriesProduct , you are consequently launching 50 new Mongo queries at once inside the forEach .如果subsubcategoriesProduct中有 50 个产品,那么您将在forEach中一次启动 50 个新的 Mongo 查询。 Each of these Product.find operations is asynchronous and will complete some time later, triggering 50 res.render .这些Product.find操作中的每一个都是异步的,将在一段时间后完成,触发 50 res.render You can't do that, you can only have one res.render .你不能那样做,你只能有一个res.render

Dealing with this kind of things using the traditional .then() syntax is complicated and easily leads to a callback hell (then inside then inside then).使用传统的.then()语法处理这类事情很复杂,很容易导致回调地狱(然后在里面然后在里面)。 Using await instead of .then() makes things way easier.使用await而不是.then()使事情变得更容易。

Also, instead of making 50 queries (one for each _id) you should make one query with an array of _id.此外,您应该使用 _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
            });

I solved my problem this way.我以这种方式解决了我的问题。

 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.

相关问题 我无法使用 sequelize 在数据库中插入数据 - I am having trouble inserting the data in the database using sequelize 我在使用PHP从Javascript提取值时遇到问题 - I am having trouble extracting a value from Javascript with PHP 我在从数组 React Native 渲染数据时遇到问题 - I am having trouble rendering data from an array React Native 我无法从嵌套的 json object 拼接元素 - I am having trouble splicing an element from a nested json object 打字稿-我在使用函数的返回值时遇到麻烦 - Typescript - I am having a trouble with using a return value from a function 我在 django 网站上工作,在正确的位置调用 function 时遇到问题 - I am working on a django website and having trouble in calling a function at the correct place 我正在尝试在 nodejs 中使用来自 DB 的搜索产品,但产品没有得到? - I am trying to use search product from DB, in nodejs but the product is not getting? 我的机器人被告知的话不会在数据库中记住。 我正在为我的机器人数据库使用 MongoDB 地图集,而我的机器人使用 discord.js - The words my bot is told are not remembered in the database. I am using MongoDB atlas for my bot's database, and my bot uses discord.js 我无法导入此文件 - I am having trouble importing this file 我在使用“removeEventListener()”时遇到问题 - I am having trouble " using "removeEventListener()"
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM