Delete a key from a MongoDB document using Mongoose

Question!

I'm using the Mongoose Library for accessing MongoDB with node.js

Is there a way to remove a key from a document? i.e. not just set the value to null, but remove it?

User.findOne({}, function(err, user){
  //correctly sets the key to null... but it's still present in the document
  user.key_to_delete = null;

  // doesn't seem to have any effect
  delete user.key_to_delete;

  user.save();
});


Answers

you can use delete user._doc.key



Could this be a side problem like using

function (user)

instead of

function(err, user)

for the find's callback ? Just trying to help with this as I already had the case.

By : Luc


I use mongoose and using any of the above functions did me the requirement. The function compiles error free but the field would still remain.

user.set('key_to_delete', undefined, {strict: false} );

did the trick for me.



This video can help you solving your question :)
By: admin