node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -


even though has been asked many times because entity has no valid objectid field.

i came across situation objectid set value can casted objectid still 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...',servicefromdb,paramerror)   } }); 

the output of code is:

but but... { servicename: 000000000000000000000001, _id: 55079a90286f49280364f78b } { [casterror: cast objectid failed value "some name" @ path "servicename"]

note servicename castable objectid mongoose uses value provided constructor instead of value set after that.

using documented set function results in same error:

servicefromdb.set('servicename','000000000000000000000001'); 

this code updates or insert entity fields set later. solution create service instance without passing argument:

servicefromdb=new service(); 

opened issue it's unintuitive behavior of document/entity use value set in constructor after re setting later.

solution create service instance without passing argument:

servicefromdb=new service(); 

Comments

Popular posts from this blog

gradle error "Cannot convert the provided notation to a File or URI" -

python - NameError: name 'subprocess' is not defined -