0

Inside a MEAN.js app, I have a schema that has a subdoc ref:

var EmployeeSchema = new Schema({
    supervisor: {
        type: Schema.Types.ObjectId, 
        ref: 'User',
    },
    ... 

I'm able to create models from the schema with or without setting the supervisor field. If the value is set at creation, then I'm able to unset it like so:

employee.supervisor = undefined;

employee.save(function(err) {
...

However, if the field value is undefined already, then I'm unable to set any values thereafter - this produces the following error:

CastError: Cast to ObjectId failed for value "[object Object]" at path "supervisor"

In fact, attempting to set the value to undefined again, with the same .save code path, will cause the same error. Where is this error coming from? What is this object it's referring to (when I'm sending it an undefined value)?

I'm relatively new to mongoose. This feels like a fundamental problem, and is most probably user error. If I'm not using the right pattern, then please let me know. I was using mongoose 3.8.8, and I moved to 3.8.23, to no avail.

EDIT: Something that may be of importance is that the supervisor is populated when the employee is returned to the client. There appears to be an issue with using the MEAN boilerplate express controller for update, that performs a _.assign of the changed state to the req.employee data that was sent to the client.

If I manually query the employee again, and set/unset the supervisor field, then I'm able to get the expected behavior with no errors. This includes setting to undefined, and setting back to a valid value. So it boils down to a combination of population + using the request data to perform the update.

Prasad Silva
  • 1,020
  • 2
  • 11
  • 28

1 Answers1

0

I think it's because undefined is failing the Schema.Types.ObjectId validation. You should use $unset as in

Employee.update({
  //whatever query
},
{
  $unset: { supervisor: true }
},
{ multi: true})
mrBorna
  • 1,757
  • 16
  • 16
  • According to [link](http://stackoverflow.com/questions/4486926/delete-a-key-from-a-mongodb-document-using-mongoose), undefined + save is equivalent to update + unset. Is this not the case? – Prasad Silva Feb 25 '15 at 01:43