javascript - MongooseJS:如何在对象数组中删除 1 个对象
问题描述
嗨MongooseJS专家!
我是MongooseJS的新手,这是我解决这个问题的第二天,但我找不到一个可行的解决方案。
先感谢您!
我的删除方法
Cart.updateOne(
{ "content.merchantId": req.body.merchantId },
{ $pull: { "content.items._id": req.body.productId } },
{ new: true },
function (error, result) {
if (error) { }
else if (result) { }
}
);
架构
const CartSchema = new Schema({
customerId: {
type: String,
required: true,
},
content: {
merchantName: {
type: String,
required: true,
},
merchantId: {
type: String,
required: true,
},
items: [],
},
});
示例 JSON
[
{
"content": {
"merchantName": "SAMPLE_MERCHANT_NAME",
"merchantId": "SAMPLE_MERCHANT_ID",
"items": [
{
"_id": "SAMPLE_ID",
"title": "SAMPLE TITLE",
}
]
},
"_id": "618220e83966345ab5d451cd",
"__v": 0
},
]
错误信息
Cannot use the part (_id) of (content.items._id) to traverse the element ({items: [{ _id: "SAMPLE_ID", title: "SAMPLE TITLE"}] })
解决方案
你应该这样使用
db.collection.update({
"content.merchantId": "SAMPLE_MERCHANT_ID"
},
{
$pull: {
"content.items": {
"_id": "SAMPLE_ID"
}
}
},
{
new:true
},
)
推荐阅读
- python - 从 pickle 文件加载 XGBoost 模型。错误:“XGBClassifier”对象没有属性“use_label_encoder”
- angular - 使用 ng-Bootstrap 调用 Stacked Modals,其中 modals 用作组件
- json - 在火花中展平json字符串
- websocket - 用户定义的自定义推送通知
- python - Python 中的 XOR 运算符示例
- jquery - 为什么在 Jquery AJAX 提交中 FormData 对象有效但不是常规对象?
- r - 使用ggplot2沿x轴重新分布列
- mysql - 使用 ? 从 node/express 服务器执行 mysql 查询 占位符出现语法错误 | npm mysql 包
- c++ - 如何在 C++ 中正确打开和关闭文件?
- javascript - 单击列表时HTML更新第二列