因此,我正在为一个学校项目学习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))
})发布于 2020-06-18 03:07:07
你为什么要通过{name: "Yoda}?此路由应该只更新名称为"Yoda“的报价吗?如果不是,那么您需要从请求对象中获取应该更新的报价。
我尝试创建一个不同的版本,假设应该更新的报价将来自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",
});
}
});https://stackoverflow.com/questions/62435995
复制相似问题