2

Schema:

var SomeSchema = new Schema({
    name: { type: String, required: true, unique: true },
    description: { type: String, required: false }
  },{ 
    versionKey: false
  }
);

// In this case the client did not pass me a description, which is ok cause this property is not required. // Why would the update fail?

var update = {name: someName, description: someDescription}; 
findByIdAndUpdate(id, update, function(err, something) { ...

Here is the error, yup cannot cast null/undefined to a String but why try?

CastError: Cast to string failed for value "undefined" at path "description"

lostintranslation
  • 23,756
  • 50
  • 159
  • 262

1 Answers1

3

The update is failing because, while you're setting description to not required, the update method will still look into the value of update.description if there is one defined in the update object. This is because, according to the docs:

The update field employs the same update operators or field: value specifications to modify the selected document.

In any case, the simple way to solve this would be to check if the description value is being passed before inserting it into the update object.

var someDescription  = req.body.args.description;
var update = {name: someName};
if(someDescription)
  update['description'] = someDescription;

On a side note, nulls are not allowed, as stated here

Community
  • 1
  • 1
verybadalloc
  • 5,768
  • 2
  • 33
  • 49
  • I had similar issue but opposite, I would love to remove description when user does not provide it, however, when I call update, the old description is still in db as I filed a question. Wonder if you have any thought on my issue? http://stackoverflow.com/questions/18858613/update-document-with-error-cast-to-string-failed-for-value-undefined – Nam Nguyen Sep 17 '13 at 20:01