• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: Replace field value with first element of an array in the same document

Resolved: Replace field value with first element of an array in the same document

0
By Isaac Tonny on 16/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

I have two models
When I delete a Vendor, 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
When I delete Vendor with mainVendorObjectId _id, I want my product to be
If I have a product with empty vendors array
After deleting Vendor with mainVendorObjectId _id I want my product to be like
I want to run it in post hook.
What I have now
but it doesn’t work and it won’t set 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.
Sample Mongo Playground

If you have better answer, please add a comment about this, thank you!

mongodb mongodb-query
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: How to set consistent decimal separators in R data frame?

26/03/2023

Resolved: How to resolve LNK2001 in c++ projects

26/03/2023

Resolved: How to correctly initialize vector of number in Typescript

26/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.