node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -
this question has answer here:
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
Post a Comment