Mongoose:找到文档后,对文档中的一个值进行迭代,并对每个值运行一个新的查询



我有一个模式,它包含对另一个模式(以及其他字段(的引用数组:

const RecipeIngredient = new Schema({
ingredientId: {                 // store id ref so I can populate later
type: Schema.Types.ObjectId,
ref: 'ingredients',
required: true
},
// there are a couple other fields but not relevant here
});
const Recipe = new Schema({
ingredients: [RecipeIngredient]
});

我正在尝试编写一条路线,它将首先通过_id找到一个配方,填充配料数组(已经有了这个功能(,最后迭代该数组中的每个配料。

router.get('/:recipeId/testing', async (req, res) => {
const { recipeId } = req.params
let recipe = await Recipe
.findById(recipeId)
.populate({ 
path: 'ingredients.ingredientId', 
model: 'Ingredient',
select: '_id ......' //I'm selecting other fields too
})
.lean()
.exec();

if (recipe) {
const { ingredients } = recipe;
const newIngredients = [];
await ingredients.forEach(async (ingr) => {
// here I'd like to be able to run a new query
// and append the result to an array outside of the forEach
// I do need information about the ingr in order to run the new query
newIngredients.push(resultOfNewQuery);
});
return res.json(newIngredients)
};

return res.status(404).json({ noRecipeFound: 'No recipe found.'});
})

我尝试过用几种不同的方法来解决这个问题,我得到的最接近的方法是在每次迭代中执行新的查询,但由于查询是异步的,所以我在实际从内部查询收集文档之前返回响应。

我也尝试在初始查询中使用.cursor(),但这对我来说不起作用,因为在recipe上的ingredients字段解析后,我确实需要访问它,然后才能迭代和运行新的查询。

任何想法都将不胜感激!如果我的方法不理想,我肯定会重新调整整个路线。

我能够通过使用for循环来实现这一点:

const newIngredients = [];
for (let idx = 0; idx < ingredients.length; idx++) {
const { fieldsImInterestedIn } = ingredients[idx];
const matchingIngredients = await Ingredient
.find(fieldsImInterestedIn)
.lean()
.exec()
.catch(err => res.status(404).json({ noIngredientsFound: 'No ingredients found' }));
newIngredients.push(ingredientsToChooseFrom[randomIndex]);
};
return res.json(newIngredients);

仍然有点困惑,为什么forEach不能工作,但我很高兴继续…

最新更新