【发布时间】: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