Daniel Beardsley
Daniel Beardsley

Reputation: 20367

Delete a key from a MongoDB document using Mongoose

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

Upvotes: 165

Views: 143745

Answers (11)

Shah Zaib
Shah Zaib

Reputation: 1

await yourModel.findByIdAndUpdate( _id, { $set: updateFields, $unset: { fieldToDelete: 1 } }, { new: true } );

Upvotes: 0

Bivin Vinod
Bivin Vinod

Reputation: 2750

if you want to remove a key from collection try this method.

 db.getCollection('myDatabaseTestCollectionName').update({"FieldToDelete": {$exists: true}}, {$unset:{"FieldToDelete":1}}, false, true);

Upvotes: 3

Jeisson Valderrama
Jeisson Valderrama

Reputation: 109

Try:

User.findOne({}, function(err, user){
  // user.key_to_delete = null; X
  `user.key_to_delete = undefined;`

  delete user.key_to_delete;

  user.save();
});

Upvotes: 2

Milad ranjbar
Milad ranjbar

Reputation: 589

the problem with all of these answers is that they work for one field. for example let's say i want delete all fields from my Document if they were an empty string "". First you should check if field is empty string put it to $unset :

function unsetEmptyFields(updateData) {
  const $unset = {};
  Object.keys(updatedData).forEach((key) => {
    if (!updatedData[key]) {
      $unset[key] = 1;
      delete updatedData[key];
    }
  });
  updatedData.$unset = $unset;

  if (isEmpty(updatedData.$unset)) { delete updatedData.$unset; }

  return updatedData;
}

function updateUserModel(data){
const updatedData = UnsetEmptyFiled(data);

    const Id = "";
    User.findOneAndUpdate(
      { _id: Id },
      updatedData, { new: true },
    );
}

Upvotes: 1

petarr
petarr

Reputation: 36

Mongoose document is NOT a plain javascript object and that's why you can't use delete operator.(Or unset from 'lodash' library).

Your options are to set doc.path = null || undefined or to use Document.toObject() method to turn mongoose doc to plain object and from there use it as usual. Read more in mongoose api-ref: http://mongoosejs.com/docs/api.html#document_Document-toObject

Example would look something like this:

User.findById(id, function(err, user) {
    if (err) return next(err);
    let userObject = user.toObject();
    // userObject is plain object
});

Upvotes: 1

Joel Esperanza
Joel Esperanza

Reputation: 17

you can use delete user._doc.key

Upvotes: -6

Noushad
Noushad

Reputation: 6781

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.

Upvotes: 54

staackuser2
staackuser2

Reputation: 12412

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

Upvotes: 249

deedubs
deedubs

Reputation: 771

You'll want to do this:

User.findOne({}, function(err, user){
  user.key_to_delete = undefined;
  user.save();
});

Upvotes: 74

Luc
Luc

Reputation: 17072

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.

Upvotes: 1

Andrew Orsich
Andrew Orsich

Reputation: 53685

At mongo syntax to delete some key you need do following:

{ $unset : { field : 1} }

Seems at Mongoose the same.

Edit

Check this example.

Upvotes: 13

Related Questions