所以我有這個字串陣列,我用它作為過濾器來使用 Mongoose 從 MongoDB 獲取檔案。我成功地從資料庫中取回了資料,但它也在Promise { <pending> }控制臺上回傳,即使我用Promise.all.
請注意,這個映射函式嵌套在兩層深for in回圈中,為簡單起見,我將其省略。
假設這是字串陣列:
const subCategories = [ 'Politics', 'Entertainment' ];
這是地圖功能:
const subCategoryID = await Promise.all( subCategories.map( async item => {
try {
const data = await SubCategory.findOne( { subCategory: item } );
return data;
} catch( e ) {
throw err;
}
}));
console.log( subCategoryID );
承諾讓我頭暈目眩。在過去的 1-2 年里,我已經嘗試學習 Promise 超過 5-6 次,但它仍然讓我感到困惑。因此,如果可以,請提供帶有 Async/Await 的解決方案。
uj5u.com熱心網友回復:
如果你只想要結果,試試這個方法:
const subCategories = [ 'Politics', 'Entertainment' ];
const queries = subCategories.map((i) => {
return { subCategory: i };
});
const subCategoryID = await SubCategory.find({
$or: queries,
});
console.log(subCategoryID);
$ormongodb手冊中解釋了使用運算子:
的
$or操作者執行兩個或更多的陣列上的邏輯或運算<expressions>和檔案選擇該的至少滿足一個<expressions>。
更多關于它在這里。
在 mongoose 中,您可以在任何find方法中使用它。
關于你的承諾的解釋,對不起,我無能為力。
如果這解決了您的問題,請標記為已回答。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/343588.html
標籤:javascript 节点.js MongoDB 异步 猫鼬
上一篇:在陣列內查找并創建或更新物件
