0

I am using mongodb 3.6.20, mongoose 5.10.9 and node 14.13.1

The case is the following. I want to insert a complex object to db. The object contains an array of objects where each object also contains an array of objects. These objects given by a client which sets the ids(O do not have power over the client to change it). I want to remove the ids and let mongo drivers to handle them and generate new ones.

what is given:

let obj = {
  property1: {
    property2: "str",
    property3: 3
  },
  property4 : [{
    _id: "a valid mongo id",
    property5: "str",
    property6: [{
      _id: "another valid mongo id",
      property7: "str"
    }]
  }]
}

what I want to provide to insert query:

let obj = {
  property1: {
    property2: "str",
    property3: 3
  },
  property4 : [{
    property5: "str",
    property6: [{
      property7: "str"
    }]
  }]
}

I have tried to remove them recursively but the call stack is exceeded. Is there any clever way I can achieve that? The option {_id: false} and {id:false} that I found on mongoose documentation are actually only for the returned documents of a query

  • maybe this will help https://stackoverflow.com/questions/31728988/using-javascript-whats-the-quickest-way-to-recursively-remove-properties-and-va – LostJon Oct 16 '20 at 11:12
  • Thanks for the comment. I have bumped into that post but as I mentioned, the recursive deletion of the properties leads to ```Maximum call stack size exceeded.``` error – konkasidiaris Oct 16 '20 at 11:28
  • 1
    There's a bug in your recursive delete. Post the code, people will help. – Matt Oct 16 '20 at 11:33

1 Answers1

1

What about this?

function removeIDs (obj) {
  Object.keys(obj).forEach(function (key) {
      if (Array.isArray(obj[key])) {
          delete obj[key][0]._id;
          return removeIDs(obj[key][0]);
      }
  });
}
removeIDs(obj)
MWO
  • 2,627
  • 2
  • 10
  • 25