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.