Search code examples
node.jsmongodbmongoosegraphql-compose

Deleting _id from object coming from mongodb doesn't work


I am using graphql to get some data from mongodb database. So, I was making an api which on running saves data in main collection but also saves data in some other collection with a couple of more data. I was trying to delete _id from the data that I get on saving on main collection but it's not working and I can't figure out why.

Here's what's happening

  const data = await User.getResolver('updateById').resolve({ //default resolver from graphql-compose library to update a record. Returns the whole document in record //
    args: {...rp.args}
  })
  const version = '4'
  const NewObject = _.cloneDeep(data.record);
  NewObject.version = version;
  NewObject.oldId = data._id;
  _.unset(NewObject, '_id'); //this doesn't work neither does delete NewObject._id//
  console.log('new obj is', NewObject, version, NewObject._id,  _.unset(NewObject, '_id')); //prints _id and surprisingly the unset in console.log is returning true that means it is successfully deleting the property//

I am very confused to what I am doing wrong.

Edit: Sorry should have mentioned, but according to lodash docs _.unset returns true if it successfully deletes a property.


Solution

  • Turn's out mongoDb makes _id as a Non configurable property. So, to do this I had to make use of toObject() method to make an editable copy of my object.

    const NewObject = _.cloneDeep(data.record).toObject();

    With this I was able to delete _id. Alternatively _.omit of lodash also works.