Delete a key from a MongoDB document using Mongoose

Daniel Beardsley picture Daniel Beardsley · Dec 20, 2010 · Viewed 85.1k times · Source

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();
});

Answer

staackuser2 picture staackuser2 · Aug 4, 2011

In early versions, you would have needed to drop down the node-mongodb-native driver. Each model has a collection object that contains all the methods that node-mongodb-native offers. So you can do the action in question by this:

User.collection.update({_id: user._id}, {$unset: {field: 1 }});

Since version 2.0 you can do:

User.update({_id: user._id}, {$unset: {field: 1 }}, callback);

And since version 2.4, if you have an instance of a model already you can do:

doc.field = undefined;
doc.save(callback);