3

Even though this has been asked many times it usually is because the entity has no valid ObjectId for the field.

I came across a situation where the ObjectId was set to a value that can be casted to ObjectId but still get this error.

The Schema:

var serviceSchema = paramMongoose.Schema({
  serviceName:{ 
   type: paramMongoose.Schema.Types.ObjectId
   , ref: 'servicenames',required:true 
  }
});

pseudo code:

serviceFromDB=new Service({serviceName:'some Name'});
serviceFromDB.serviceName='000000000000000000000001';
serviceFromDB.save(function(paramError,paramData){
  if(paramError){
    console.log('but but but...',serviceFromDB,paramError)
  }
});

The output of this code is:

but but but... { serviceName: 000000000000000000000001, _id: 55079a90286f49280364f78b } { [CastError: Cast to ObjectId failed for value "some Name" at path "serviceName"]

Note that the serviceName is castable to ObjectId but mongoose uses the value provided to the constructor instead of the value set after that.

Using the documented set function results in the same error:

serviceFromDB.set('serviceName','000000000000000000000001');

This was code that updates or insert an entity so fields are set later. Solution was to create a service instance without passing an argument:

serviceFromDB=new Service();

Opened an issue for this as it's very unintuitive behavior of a document/entity to use a value set in the constructor even after re setting it later.

chridam
  • 100,957
  • 23
  • 236
  • 235
HMR
  • 37,593
  • 24
  • 91
  • 160
  • 1
    A completely irrelevant answer marked as a duplicate? I can google and use the so search as well my friend but that answer has nothing to do with what caused the problem. A lot of things could cause this error like querying or trying to populate using a non casteble value. The problem here describes a save operation and even in the error the object logged has a valid object id yet mongoose tries to cast a value to ObjectId that is no longer the current value. – HMR Mar 17 '15 at 04:39
  • 2
    Yeah, I think they jumped the gun a bit quick on this one. Reviewers please note that this is the same error as the duplicate but a different cause and fix. – smathy Mar 17 '15 at 07:23

1 Answers1

3

Solution was to create a service instance without passing an argument:

serviceFromDB=new Service();
HMR
  • 37,593
  • 24
  • 91
  • 160