简体   繁体   中英

Delete / remove am empty array from object from javascript using mongoose

I have database collection, that looks like this, how to remove this empty array.

Initially I have object in this (HUE) array Which looks like this

  "HUE": [{
        "chartId": "timeseries",
        "name": "TS",
       
    }]

, but after deleting the objects, it does not delete the empty array

{
 
"userId": "adam",
"charts": {
    "HUE": [],
    "Color": [{
        "chartId": "one",
        "name": "TS",
       
    }]
  }
}

PS I only want to delete the HUE array when its empty

     delChartObj.updateOne(
    { 'userId': userId },
    { $pull: query } // this line actually find the chartId and delete it 
  // after the above line, I actually want to check, if after del the object , array became empty, then delete the array too
  , function (err, obj) {
if (err) { res.send.err }

res.status(200).send("Deleted Successfully");
    });

If you want to filter the array and then if empty to delete the array, you can do the bellow

db.collection.update(
{
  "$expr" : {
    "$eq" : [ "$userId", "adam" ]
  }
},
[ {
  "$addFields" : {
    "charts.HUE" : {
      "$filter" : {
        "input" : "$charts.HUE",
        "as" : "hue",
        "cond" : {
          "$ne" : [ "$$hue.chartId", "timeseries" ]
        }
      }
    }
  }
}, {
  "$addFields" : {
    "charts.HUE" : {
      "$cond" : [ {
        "$eq" : [ {
          "$size" : "$charts.HUE"
        }, 0 ]
      }, "$$REMOVE", "$charts.HUE" ]
    }
  }
} ]
)

Test code here

Its pipeline update requires MongoDB >= 4.2 Pipeline updates are very powerful, but for simple updates they can be more complicated.

$$REMOVE is a system variable, if a field gets this value, its removed. Here the field gets this value only if empty array.

db.collection.update({userId, 'charts.HUE': {$exists:true, $size:0}}, { $unset: { 'charts.HUE': 1 } })

It works -> https://mongoplayground.net/p/uqU7d0Kp2eL

Update: The question changed and this solution is not completely correct. Users have to ask with more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM