Mongoose error findByIdAndUpdate fails in cast

Trying to update a document using findByIdAndUpdate, i get an error that i don't understand.

    console.log(req.body);
    var data = req.body;
    data._id = undefined;
    Package.findByIdAndUpdate(req.params.id, data, function (err, pkg) {
        if (err) {
            console.log(err.stack);
            return next(restify.InternalServerError(err));
        }
        res.json(pkg);
        next();
    });

I get the following error:

TypeError: Cannot read property '_id' of undefined
at ObjectId.cast (/home/ubuntu/workspace/server/node_modules/mongoose/lib/schema/objectid.js:109:12)
at ObjectId.castForQuery (/home/ubuntu/workspace/server/node_modules/mongoose/lib/schema/objectid.js:165:17)
at Query._castUpdateVal (/home/ubuntu/workspace/server/node_modules/mongoose/lib/query.js:2009:17)
at Query._walkUpdatePath (/home/ubuntu/workspace/server/node_modules/mongoose/lib/query.js:1969:25)
at Query._castUpdate (/home/ubuntu/workspace/server/node_modules/mongoose/lib/query.js:1865:23)
at castDoc (/home/ubuntu/workspace/server/node_modules/mongoose/lib/query.js:2032:18)
at Query._findAndModify (/home/ubuntu/workspace/server/node_modules/mongoose/lib/query.js:1509:17)
at Query.findOneAndUpdate (/home/ubuntu/workspace/server/node_modules/mongoose/node_modules/mquery/lib/mquery.js:2056:15)
at Function.Model.findOneAndUpdate (/home/ubuntu/workspace/server/node_modules/mongoose/lib/model.js:1250:13)
at Function.Model.findByIdAndUpdate (/home/ubuntu/workspace/server/node_modules/mongoose/lib/model.js:1344:32)

I have verified that the id is valid, data is a valid object as well.

My model:

mongoose.model('Package', {
    name: {
        required: true,
        type: String
    },
    servers: [mongoose.Schema.Types.ObjectId],
    packageType: {
        type: String,
        enum: ['package', 'subscription']
    },
    subscriptionPeriodInDays: Number,
    pointsIncluded: Number,
    price: Number,
    rank: String,

    data: mongoose.Schema.Types.Mixed //For custom solutions
});

The log also prints a valid data object

{
    name: 'Your Package',
    packageType: 'subscription',
    subscriptionPeriodInDays: 30,
    pointsIncluded: 10000,
    price: 10,
    rank: 'Donator',
    _id: undefined,
    __v: 0,
    servers: [],
    description: '<p>test</p>\n'
}

I have tried to step trough with the debugger but i couldn't find a reason for this.

As Raleigh said, you need to remove _id field. You can do it by delete data._id; instead of data._id = undefined;.

I believe Mongoose is trying to set the value of _id to undefined since the _id value is still getting passed in via the data object.

Try removing the line data._id = undefined; before you update the model or completely remove the _id field from the data object.