node.js - 使用更新拉取从数组中删除一个元素的问题
问题描述
我正在使用 mongoose 和 express 作为我的后端,我正在尝试从单个 Mongodb 文档中的订单数组中删除一个数组元素。这可能吗?我在网上搜索过,但只找到了如何使用过滤器删除所有元素或弹出数组中的第一个或最后一个元素。
目前我正在后端执行此操作,但是这会删除 item_id 等于 data.response[0].item_id 的每个订单元素。
user.updateOne({ "username": data.username },{"$pull": { "orders": {"item_id": data.response[0].item_id}}},{safe: true });
这行代码在 item_id 为 1 时删除订单内的两个元素但是我只希望它删除它找到的第一个元素 item_id: 1
用户集合的示例 Mongodb 文档部分
{
"_id": "60a906402342852b483341a6",
"username": "qwer",
"password": "qwer",
"orders": [
{
"_id": "609cf4d4e4ecce2348139686",
"item_id": 1,
"item_name": "toothbrush",
"item_price": 28,
"item_category": "dental",
"item_currency": "$",
"item_description": "standard toothbrush",
"item_image": "https://cdn.shopify.com/s/files/1/1704/0849/products/ToothBrushTeal_bc4c6c15-cf79-4bb5-87cc-28109b5e7605_1024x1024.jpg?v=1607029152"
},
{
"_id": "609cf4d4e4ecce2348139686",
"item_id": 1,
"item_name": "toothbrush",
"item_price": 28,
"item_category": "dental",
"item_currency": "$",
"item_description": "standard toothbrush",
"item_image": "https://cdn.shopify.com/s/files/1/1704/0849/products/ToothBrushTeal_bc4c6c15-cf79-4bb5-87cc-28109b5e7605_1024x1024.jpg?v=1607029152"
}
]
}
解决方案
您可能想查看此论坛https://developer.mongodb.com/community/forums/t/pull-only-one-item-in-an-array-of-instance-in-mongodb/12928 使用聚合更新,如第一个答案所示。你的代码应该是这样的:
user.updateOne({ "username": data.username },[
{ $set: {
orders: {
$let: {
vars: { ix: { $indexOfArray: [ "$orders", data.response[0].item_id ] } },
in: { $concatArrays: [
{ $slice: [ "$orders", 0, "$$ix"] },
[ ],
{ $slice: [ "$orders", { $add: [ 1, "$$ix" ] }, { $size: "$orders" } ] }
]
}
}
}
}}],{safe: true });
推荐阅读
- git - git fetch 远程分支,但在本地存储库或工作副本中看不到
- microsoft-teams - 在 MS Teams 中部分呈现的自适应卡片图像
- python - 如何删除以python中的某个字符串结尾的数据框中的某些列表成员
- python - 如何接受字符串作为参数?(discord.py 重写)
- r - 只预测一个值
- json - 有没有办法在 NIFI 中将 JSON 转换为 Protobuf?
- swagger - OpenApi 3.0:对现有类的引用
- python - pandas.Timedelta 在浮点数中转换为秒太慢
- java - 如何驱逐多个 pod 中的缓存?我有两个 Openshift pod,我想在两个 pod 中发送一个驱逐缓存的 HTTP 请求
- maven - 两次执行 mvn --encrypt-master-password 或 --encrypt-password 如何用同一个词获得两个不同的结果?