Delete a key from a MongoDB document using Mongoose

前端 未结 11 1155
我寻月下人不归
我寻月下人不归 2020-11-27 04:38

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 n

相关标签:
11条回答
  • 2020-11-27 04:58

    You'll want to do this:

    User.findOne({}, function(err, user){
      user.key_to_delete = undefined;
      user.save();
    });
    
    0 讨论(0)
  • 2020-11-27 04:58

    Try:

    User.findOne({}, function(err, user){
      // user.key_to_delete = null; X
      `user.key_to_delete = undefined;`
    
      delete user.key_to_delete;
    
      user.save();
    });
    
    0 讨论(0)
  • 2020-11-27 05:01

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

     db.getCollection('myDatabaseTestCollectionName').update({"FieldToDelete": {$exists: true}}, {$unset:{"FieldToDelete":1}}, false, true);
    
    0 讨论(0)
  • 2020-11-27 05:03

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

    { $unset : { field : 1} }
    

    Seems at Mongoose the same.

    Edit

    Check this example.

    0 讨论(0)
  • 2020-11-27 05:04

    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
    });
    
    0 讨论(0)
  • 2020-11-27 05:07

    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.

    0 讨论(0)
提交回复
热议问题