[英]How to check if there are no more documents to update using findOneAndUpdate
所以我正在為一個學校項目學習 CRUD,我遵循了一個非常有用的教程。 但是,當我完成它時,我注意到當沒有更多要更新的報價時,它仍然會更新報價。 我該如何更改它以停止更新甚至不存在的報價?
app.put('/quotes', (req, res) => {
quoteCollection.findOneAndUpdate(
{ name: 'Yoda' },
{
$set: {
name: req.body.name,
quote: req.body.quote
}
},
{upsert: true}
)
.then(result => {
//The if block that i am trying
if (result.deletedCount === 0) {
return res.json('No quote to delete')
}
})
.catch(error => console.error(error))
})
你為什么要傳遞{name: "Yoda}
?這條路線應該只更新以 "Yoda" 作為其名稱的報價?如果沒有,那么你需要從請求 object 中獲取應該更新的報價。
我嘗試創建一個不同的版本,基於應該更新的報價將來自 req.body 的假設:
app.put("/quotes", async (req, res) => {
//Grab the name/id/identifier for the quote you want to update from the body
const query = req.body.name;
// Try to update the document on the database
try {
const result = await quoteCollection.findOneAndUpdate(
query,
{
name: req.body.name,
quote: req.body.quote,
},
{
upsert: true,
new: true,
}
);
// If it worked, it will return the updated quote
res.status(200).json({
status: 200,
data: {
result,
},
});
} catch (err) {
res.status(400).json({
status: 400,
message: "Something went wrong",
});
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.