当产品被删除时,我正在try 从用户购物车中删除该产品.

我的用户架构:

const userSchema = new Schema({
    username: { type: String, required: true },
    phone: {
        type: String,
        match: [/\d{10}/, 'Phone number should only 10 have digits'],
    },
    email: {
        type: String,
        match: [/\S+@\S+\.\S+/, 'Email must be valid'],
        required: [true, 'Email must be valid'],
        unique: true,
    },
    password: {
        type: String,
        required: [true, 'Password is not valid'],
    },
    cart: {
        items: [
            {
                productId: {
                    type: Schema.Types.ObjectId,
                    ref: 'Product',
                },
                quantity: {
                    type: Number,
                    max: [10, 'Only 10 quantity of one item can be added.'],
                    required: true,
                },
            },
        ],
        total: { type: Number, default: 0 },
    },
    admin: { type: Boolean, default: false },
    addresses: [addressSchema],
});

我try 使用以下代码从Items数组中删除该项:

await User.updateMany({}, { cart: { $pull: { 'items.productId': id } } });

但是,这会删除整个购物车对象,而不是单个项目.请谁来帮帮我.

推荐答案

看一下这个官方的例子Remove All Items That Equal a Specified Value

{ $pull: { <field1>: <value|condition>, <field2>: <value|condition>, ... } }

field1应该是一个数组,cart.items是一个array.这意味着我们从cart.items数组中提取一些元素.

db.collection.updateMany({},
{
  $pull: {
    "cart.items": {
      productId: 2
    }
  }
})

输入:

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    cart: {
      items: [
        {
          productId: 1
        },
        {
          productId: 2
        },
        {
          productId: 3
        },
        
      ]
    }
  }
]

输出:

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "cart": {
      "items": [
        {
          "productId": 1
        },
        {
          "productId": 3
        }
      ]
    }
  }
]

mongoplayground

Node.js相关问答推荐

使用OpenAI API时遇到问题

对接Nestjs/VueJS应用程序

NPM:一般的npm二进制依赖可以静态构建吗?

对于具有重叠列的组合键,在冲突&q;上没有唯一或排除约束匹配错误

Sequelize、postgres和posgis:在n°;公里

Solidity 将数据位置从内存更改为存储

当我try 从本地主机发布新产品时收到错误消息

一个非常奇怪的JavaScript heap out of memory问题

Sharp JS 依赖关系 destruct 了 Elastic Beanstalk 上的 Express Server

bash:npm:找不到命令?

在 ExpressJS 中将变量传递给 JavaScript

在多个文件 node.js 之间共享和修改变量

使用 nvm-windows 时更新 npm

如何在 Mongoose 模式中设置数组大小限制

安全沙箱并执行用户提交的 JavaScript?

TypeError:请求路径包含未转义的字符,我该如何解决这个问题

安装 node.JS 时,node.js 运行时和 npm 包管理器选项有什么区别?

在单独的模块中定义 Mongoose 模型

使用 Node.js 和 Express 进行简单的 API 调用

使用 node 的内置调试器判断变量?