第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

如何使用貓鼬更新 MongoDB 中的數(shù)組?

如何使用貓鼬更新 MongoDB 中的數(shù)組?

溫溫醬 2022-05-26 14:22:36
我有兩個(gè)模式,用戶(hù)和產(chǎn)品。用戶(hù)模式是我存儲(chǔ)所有產(chǎn)品 ID 和用戶(hù)添加到購(gòu)物車(chē)的商品數(shù)量的地方。當(dāng)用戶(hù)向“/checkout”發(fā)出請(qǐng)求時(shí),它應(yīng)該更新數(shù)量,然后將其從購(gòu)物車(chē)中刪除。我在結(jié)帳時(shí)遇到問(wèn)題沒(méi)有更新數(shù)量。router.post('/checkout', auth, catchAsync(async (req, res) => {    const user = await User.findById(req.session.userId);    const err = [];    if (user && user.products.length > 0) {        user.products.map(async (product) => {            let total = 0;            const p = await Product.findById(product.productID);            if (p.quantity > 0 && p.quantity > product.quantity) {                console.log('IN');                total = p.quantity - product.quantity;                console.log(total);                await Product.findOneAndUpdate({ _id: product.productID }, { $set: { quantity: total } });            } else {                err.push(`Item, ${p.name} is sold out`);            }        });        await User.findOneAndUpdate({ _id: req.session.userId }, { $set: { products: [] } });        if (err.length) {            return res.status(500).json({ message: err });        }        return res.status(200).json({ message: 'OK' });    }    return res.status(200).json({ message: 'Empty cart' });}));用戶(hù)架構(gòu):產(chǎn)品架構(gòu):
查看完整描述

1 回答

?
莫回?zé)o

TA貢獻(xiàn)1865條經(jīng)驗(yàn) 獲得超7個(gè)贊

我相信您的代碼中的問(wèn)題出在user.products.map(...)函數(shù)上,因?yàn)槟肋h(yuǎn)不會(huì)等待您在地圖中創(chuàng)建的所有承諾都得到解決。


換句話(huà)說(shuō),該map函數(shù)返回一個(gè)待處理的 Promise 數(shù)組,但它不會(huì)等待它們完成,因此執(zhí)行會(huì)繼續(xù)執(zhí)行,直到到達(dá)res.status(...)任何代碼map執(zhí)行之前的其余代碼。


你有不同的選擇來(lái)解決它,但主要是你需要處理map函數(shù)返回的承諾數(shù)組并等待它們完成,然后再結(jié)束你的代碼。async/await在Google Developers Web 基礎(chǔ)指南中有一個(gè)很好的解釋如何處理這種情況。


我通常利用Promise.all()函數(shù),它從承諾數(shù)組中返回一個(gè)承諾,因此您可以等到代碼中的代碼為數(shù)組中的每個(gè)項(xiàng)目并行map執(zhí)行(即在您的情況下)。您可以在MDN 文檔中閱讀更多相關(guān)信息。product


// ...


let promisesArray = user.products.map(async product => {...});

// promisesArray should look like: [Promise { <pending> }, Promise { <pending> }, … ]


// Using Promise.all we wait for each of them to be done in parallel

await Promise.all(promisesArray);


// Now you are certain the code in the map has been executed for each product


// ...

一個(gè)好的做法是使用try {} catch(err) {}塊Promise.all()來(lái)處理某些承諾被拒絕的情況


查看完整回答
反對(duì) 回復(fù) 2022-05-26
  • 1 回答
  • 0 關(guān)注
  • 111 瀏覽
慕課專(zhuān)欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢(xún)優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)