[英]await is causing my update in findOneAndUpdate to run twice
我正在使用 findOneAndUpdate() 設置基於 function 的變量,並且需要其他所有內容等到設置變量。 但是,當我這樣做時,更新會運行兩次,因為我在它之前使用了“等待”。
documentUpdate = { $set: { price: price }, $push: { ips: ipa }, $inc: { likes: 1 }};
returnObject = await getStockWithTrue(stockName, documentUpdate, price);
我稍后嘗試返回 object 並且僅在我使用 await 時才有效。 如果我將 await 帶走,則 function 工作正常(僅更新一次)並發送到 mongoDB,但隨后無法使用變量 returnObject。
例如,如果我使用 await,則返回 Object 將推送 ip 地址兩次,並將喜歡的次數增加 2。然后。 如果我將 await 帶走,則 returnObject 不是 getStockWithTrue() 返回的正確 model 因為一切都在完成之前執行。
這是使用 findOneAndUpdate() 的 getStockWithTrue function
const getStockWithTrue = (stockName, updateDocument, price) => {
return Stock.findOneAndUpdate(
{ stock: stockName },
updateDocument,
{ new: true, upsert: true },
(error, stock) => {
if (error) return console.log(error);
// If stock is not already in database
if (!error && !stock) {
stock = new Stock({
stock: stockName,
price: price,
likes: 1,
ips: ipa,
});
}
stock.save((error, result) => {
if (error) return console.log(error);
else return result;
});
}
);
};
我確信有一個簡單的解決方案可以解決這個問題,但我已經研究了好幾天了,因為我一直沒有找到答案。 任何和所有的幫助表示贊賞!
我認為您的代碼過於復雜。 當您使用upsert: true
時,您不需要手動檢查庫存並創建(如果它不存在)。 如果文檔不存在,則upsert選項將創建一個文檔。
您的代碼的簡化版本可能是:
documentUpdate = { $set: { price: price }, $push: { ips: ipa }, $inc: { likes: 1 }};
returnObject = await getStockWithTrue(stockName, documentUpdate, price);
然后稍后
const getStockWithTrue = async (stockName, documentUpdate) => {
return await Stock.findOneAndUpdate(
{ stock: stockName },
documentUpdate,
{
upsert: true,
new: true
}
)
}
讓我知道它是否有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.