Skip to content

Trying to delete/set null a field with findOneAndUpdate #4529

@enrichz

Description

@enrichz

I'm trying to delete (also setting it to null would be acceptable as a backup plan) the field "board" from a document that looks like this:

var cardSchema = new Schema({
  title: {
    type: String,
    required: true
  },
version: {
    type: Number,
    required: true,
    "default": 0
  },
  board: {
    type: ObjectId,
    ref: 'Board'
  },
},{strict: false});
mongoose.model('Card', cardSchema);

For my scenario, I need to use the function findOneAndUpdate in the following way:

var cardChanges = {board: undefined, version: 10};
Card
  .findOneAndUpdate({_id: "my_id"}, cardChanges, 
      {"new": true, upsert: false, passRawResult: false, 
        "overwrite": false, runValidators: true, 
         setDefaultsOnInsert: true})
  .exec(function(err, result) {
    if(err) {
      // error handlers
    }
    if(!result) {
      // No card to be updated
    }
    // ok
  });

Before the update I have the document:

{
_id: "my_id",
title: "This is my card",
board: "my_board",
version: 9
}

And after:

{
_id: "my_id",
title: "This is my card",
board: "my_board",
version: 10
}

I tried to set the board with both null and undefined, the result is the same.
For my use case I can't use the save method.
Mongoose 4.5.5, MongoDB 3.2.9
Any idea or workaround?

Thanks

Metadata

Metadata

Assignees

No one assigned

    Labels

    can't reproduceMongoose devs have been unable to reproduce this issue. Close after 14 days of inactivity.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions