gpt4 book ai didi

node.js - 使用 express 循环 mongoose 模式函数,将数据收集到一个数组中,最后用所有数据呈现页面

转载 作者:可可西里 更新时间:2023-11-01 10:11:39 27 4
gpt4 key购买 nike

Nodejs +Express+Mongoose初学者问题:

*所以我遇到了这个问题,我有一个类别数组(服装类别)。对于每个类别,我想从数据库中获取结果。所以我做了一个正常人会做的事。我使用了一个 for 循环,获取产品,存储在一个数组中,然后获取下一个产品,存储在同一个数组中等等......(男性和女性的过程相同)。现在我想用数据呈现我的 View ,但由于 Node js 的异步性质,它不可访问。我完全理解。所以我正在寻找的是我的问题的替代/解决方案 *

我的 express 代码更好地解释了我的痛苦。请看:

//INDEX PAGE
router.get('/', (req, res, next) => { //anonymous callback function
let allCategories;
let womenFashion = [],
menFashion = [];
Clothing.groupByBodyPart(function(err, categories) {
if (categories) {
allCategories = categories.slice(0);
for (let i = 0; i < allCategories.length; i++) { //looping
let category = allCategories[i]._id; //gives a category, eg.,footwear,bottomwear
Clothing.getCategoryWise(category, 'M', function(err, products) { //products here will be an array of objects
if (products) {
menFashion[i] = products.slice(0); //storing products into an array for future use
console.log(menFashion[i]); //accessible here one at a time Eg.,[{slippers},{shoes}]
}
});
Clothing.getCategoryWise(category, 'F', function(err, products) {
if (products) {
womenFashion[i] = products.slice(0); //same as above
console.log(womenFashion[i]); //same as above
}
});
}
}
console.log(menFashion[0]); // not accessible here, so I can't render my page
res.render('index.pug', {
allCategories,
menFashion,
womenFashion
}); //won't work as menFashion and womenFashion aren't available
});
});

这里是 mongoose 静态函数:

//get categorywise  products
clothingSchema.statics.getCategoryWise = function(bodyPart,gender,callback){
Clothing.aggregate([
{ $match: {'category.bodyPart': bodyPart,
'category.gender': gender
}
},
{ $group: {_id: "$category.type" }
},
{ $sort: {_id: 1 }
}
])
.exec((err,products)=>{
if(err){
return callback(err);
}else if(!products){
let err = new Error('No Product Found!');
err.status = 401;
return callback(err);
}
return callback(null,products);
});
}

仅作记录

一切都很好,我只是在呈现我的页面时遇到问题,因为 menFashion 和 womenFashion 数组在回调之外不可访问。

提前致谢:)

更新:

我自己解决了,但仍然感谢大家(特别是@faiz)

我的解决方案基本上包括嵌套:

//INDEX PAGE
router.get('/',(req,res,next)=>{ //anonymous callback function
let allCategories;
let womenFashion = [], menFashion = [];
Clothing.groupByBodyPart(function(err,categories){
if(categories){
allCategories = categories.slice(0);
for(let i = 0; i < allCategories.length; i++){ //looping
let category = allCategories[i]._id; //gives a category, eg.,footwear,bottomwear
Clothing.getCategoryWise(category,'M',function(err,products){ //products here will be an array of objects
if(products){
menFashion.push(products);
menFashion[i] = products.slice(0); //storing products into an array for future use
//console.log(menFashion[i]); //accessible here on at a time Eg.,[{slippers},{shoes}]
}
Clothing.getCategoryWise(category,'F',function(err,products){
if(products){
womenFashion[i] = products.slice(0); //same as above
//console.log(womenFashion[i]); //same as above
}
if(i == allCategories.length-1){
console.log('men',menFashion); //everything accessible
console.log('men',menFashion); //everything accessible
res.render('index.pug',{allCategories,menFashion,womenFashion}); //tadaaaaaaaa
}
});
});
}
}
});
});

最佳答案

你可以使用这样的东西。

我使用了两个 Promise.all 调用来确保您有两个可以使用的结果。您也可以使用一个 Promise.all

router.get('/', (req, res, next) => { //anonymous callback function
let allCategories;
let womenFashion = [],
menFashion = [];
Clothing.groupByBodyPart(function (err, categories) {
if (categories) {
allCategories = categories.slice(0);
const menPromises = [];
const womenPromises = [];
for (let i = 0; i < allCategories.length; i++) { //looping
let category = allCategories[i]._id; //gives a category, eg.,footwear,bottomwear
menPromises.push(
new Promise((resolve, reject) => {
Clothing.getCategoryWise(category, 'M', function (err, products) { //products here will be an array of objects
if (products) {
menFashion[i] = products.slice(0); //storing products into an array for future use
resolve(menFashion[i]);
console.log(menFashion[i]); //accessible here one at a time Eg.,[{slippers},{shoes}]
}
})
})
);
womenPromises.push(
new Promise((resolve, reject) => {
Clothing.getCategoryWise(category, 'F', function (err, products) { //products here will be an array of objects
if (products) {
womenFashion[i] = products.slice(0); //storing products into an array for future use
resolve(womenFashion[i]);
console.log(womenFashion[i]); //accessible here one at a time Eg.,[{slippers},{shoes}]
}
})
})
);
}

Promise.all([Promise.all(menPromises), Promise.all(womenPromises)]).then(([menResults, womenResults]) => {
console.log(menFashion[0]); // not accessible here, so I can't render my page
res.render('index.pug', {
allCategories,
menFashion,
womenFashion
}); //won't work as menFashion and womenFashion aren't available
});
}
});
});

关于node.js - 使用 express 循环 mongoose 模式函数,将数据收集到一个数组中,最后用所有数据呈现页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48848536/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com