我要知道,我将如何这样做。
I have a webshop that I m working on for school. This is the category array I would like to remove from the object (the one inside "products"):
我的法典如下:
webshopCollection.findByIdAndUpdate(req.body.webshop, {
categories: { $pull: { products: productId } },
});
这并不可行。 它不去掉我从前言中指明的产品(我确保收到请求,即)
How would I go about removing said value from the array?
我也努力这样做:
webshopCollection.findByIdAndUpdate(req.body.webshop, {
$pull: { categories: { products: productId } },
});
但没有结果。
正式职能守则:
const productId = req.body.productId;
productsCollection
.deleteOne({ _id: productId })
.then(() =>
webshopCollection.findByIdAndUpdate(req.body.webshop, {
$pull: { products: productId },
})
)
.then(() => {
webshopCollection.findByIdAndUpdate(
req.body.webshop,
{
$pull: {
"categories.$[category].products": productId,
},
},
{
arrayFilters: [
{
"category.products": productId,
},
],
}
);
})
.then(() => {
return res
.status(200)
.json({ message: "Product deleted successfully" });
})
.catch((error) => {
console.log(error);
return res
.status(400)
.json({ error: "Something went wrong. Please try again later" });
});
<><>UPDATE: 我确定
const productId = req.body.productId;
await productsCollection.deleteOne({ _id: productId });
await webshopCollection.findByIdAndUpdate(req.body.webshop, {
$pull: { products: productId },
});
await webshopCollection
.findByIdAndUpdate(
req.body.webshop,
{
$pull: {
"categories.$[category].products": productId,
},
},
{
arrayFilters: [
{
"category.products": productId,
},
],
}
)
.then(() => {
return res
.status(200)
.json({ message: "Product and references deleted successfully" });
})
.catch((error) => {
return res
.status(400)
.json({ error: error });
});
它肯定与所有“原始”承诺有关。 我把所有东西推向“awa”,似乎工作:
希望能帮助人们随机地与我一样地遇到同样的问题。 你们永远不知道。