Delete is not working for javascript object in NodeJs Delete is not working for javascript object in NodeJs mongodb mongodb

Delete is not working for javascript object in NodeJs


It looks like the reason you can't delete some of those properties is that they have been defined as "non-configurable." However, your approach is sub-optimal because it necessarily mutates its argument. Never, ever, mutate an argument. Ever.

Rather than delete properties from event, you ought to construct a new object that contains only the properties you desire.

  • you can safelist specific properties that you wish to transfer (and save)
  • you can blocklist specific properties that you don't wish to save
  • you can transfer only those properties that live directly on the object, rather than the prototype chain, using Object.getOwnPropertyNames

Libraries like lodash have sugar for doing this kind of thing:

// safelist (using lodash)var saveableEvent = _.pick(event, ['code', 'event', 'source', 'target', 'params', 'log', 'hits', 'type', 'state', 'testProperty', 'updatedDate', 'creationDate']);// or blocklist (using lodash)var saveableEvent = _.omit(event, ['_id', '__t', '__v']);// only copy object's own properties (without lodash)var saveableEvent = Object.getOwnPropertyNames(event).reduce(function(out, propName) {    return Object.assign(out, event[propName])}, {})// create editable copy of object, then remove undesired propsvar saveableEvent = event.toObject();delete saveableEvent._id;


Did you try lean() when you query?like find(query).lean()... check this http://blog.sandromartis.com/2016/05/08/mongoose-lean/This will allow you to do any operation to the object.

Other way could be extending the root object with removing unwanted properties from it. you can use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

example:

var obj = { a: 1 };var copy = Object.assign({}, obj);console.log(copy); // { a: 1 }delete copy._id;//or whatever you wantconsole.lg(copy);//check this doesnt have the _id;

ThanksHope this helps


I recently had a similar problem. I used loadash to cut off the values I didn't need from the array, but had to use .toObject() in the fetched object so I could use it as an argument. Something like:

let resultExample = _.omit(exampleObject.toObject(), ['x', 'y', 'z']);