Question:
I have two modelsVendor
, I want all Products
with mainVendor
field of deleted Vendor
‘s _id
to be replaced with the first vendor
of vendors
array. If vendors
array is empty, I want mainVendor
to be set to null
.Say I have
Product
Vendor
with mainVendorObjectId
_id
, I want my product
to beproduct
with empty vendors
arrayVendor
with mainVendorObjectId
_id
I want my product to be likepost
hook.What I have now
mainVendor
to null
if vendors
array is empty.Answer:
A bit long query, but you can try with Update with aggregation pipeline.With
$cond
operator to check whether vendors
is an empty array, if yes set null
, else take the first value from the vendors
array to mainVendor
field.For the
vendors
field, it does the same concept as mainVendor
field, the outcome will be different in removing the first item from vendors
array.If you have better answer, please add a comment about this, thank you!