【问题标题】:How to remove subdocument (by Id) embedded in sub array in MongoDB?如何删除嵌入在 MongoDB 子数组中的子文档(按 Id)?
【发布时间】:2019-07-03 08:58:18
【问题描述】:
ProductCollection: 
{
  _id: { ObjectId('x1')},
  products: [ 
              { listPrice: '1.90', product: {id: 'xxx1'} },
              { listPrice: '3.90', product: {id: 'xxx2'} },
              { listPrice: '5.90', product: {id: 'xxx3'} }
            ]
},
{
  _id: { ObjectId('x2')},
  products: [ 
              { listPrice: '2.90', product: {id: 'xxx4'} },
              { listPrice: '4.90', product: {id: 'xxx5'} },
              { listPrice: '5.90', product: {id: 'xxx6'} }
            ]
},

我想从集合 (x1) 中删除子文档 (xxx3),然后尝试以下操作:

ProductCollection.update(
{ 
  "_id": mongoose.Types.ObjectId('x1')  
}, 
{ 
  $pull : { 'products.product': {id: 'xxx3' } } 
} 

它似乎不起作用。谁能帮帮我吗?谢谢

【问题讨论】:

  • 应该是{ $pull : { 'products': { 'product.id': 'xxx3' } } }
  • @Winzlet:我试过了(似乎类似于下面的 kmreko 建议,除了“产品”的报价)。它给出了相同的结果并向我抛出了这个错误: UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "xxx1" at path "product"。接下来,我也尝试了: $pull : { 'products': { 'product._id': mongoose.Types.ObjectId('5baa131b36d6a02b442b4b5e') } }。这次没有错误,但什么也没发生。子文档还在,这里有什么问题吗?谢谢
  • @Winzlet:与上面的建议相同,我使用以下代码切换到匹配 '_id':$pull : { products: { 'product': { 5baa131b36d6a02b442b4b5e } } }。它完美地工作。谢谢

标签: mongodb pull subdocument


【解决方案1】:

在创建 mongoose 架构时添加此 _id: {id: false}

例如:

partners:[{
    name: { type: String, default: '' },
    logo: { type: mongoose.Schema.Types.Mixed, default: '' },
    _id: { id: false }
  }],

【讨论】:

    【解决方案2】:

    $pull 的字段需要是数组。

    这应该可行:

    $pull: { products: { 'product.id': 'xxx3' } }
    

    【讨论】:

    • 我试过了,但它抛出了这个错误: UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "xxx1" at path "product"。接下来,我也尝试了: $pull : { 'products': { 'product._id': mongoose.Types.ObjectId('5baa131b36d6a02b442b4b5e') } }。这次没有错误,但什么也没发生。子文档还在,这里有什么问题吗?谢谢
    • 我认为您的建议是正确的,我使用以下代码切换到匹配 '_id':$pull : { products: { 'product': { 5baa131b36d6a02b442b4b5e } } }。它完美地工作。谢谢
    猜你喜欢
    • 1970-01-01
    • 2014-03-30
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2013-07-23
    • 1970-01-01
    • 2023-03-28
    • 2017-08-22
    相关资源
    最近更新 更多