In Mongoose, what value do I pass in for object property to get the default value from the schema? -
in mongoosejs, i'm trying create new instance of model based on post data. in cases want field have default value defined on schema, when pass in null
or undefined
value of property, i'm not getting default in resulting mongo object (i default when don't pass in property @ all).
var objschema = mongoose.schema({ foo: { type: number, default: 10 }, bar: { type: number, default: 10 }, baz: { type: number, default: 10 } }); var obj = db.model('obj', objschema) // note `baz` not passed in below var obj = new obj({ foo: null, bar: undefined }); obj.save(function(err, savedobj){ console.log(savedobj) // { foo: null, baz: 10 } });
i'd prefer not have write separate object instantiation code each potential permutation of properties might not have values, there can set foo
, bar
result in default value? seems should common case me, maybe i'm missing something?
i think, should add setter schema below. works when add new record. when update documents doesn't work. hope helps;
function inspector (val) { if (typeof val == "object" || typeof val == "undefined" || typeof val == "string" || val == 0) return 10; else return val; } var objschema = mongoose.schema({ foo: { type: number, default: 10, set: inspector }, bar: { type: number, default: 10, set: inspector }, baz: { type: number, default: 10, set: inspector }, qux: { type: number, default: 10, set: inspector } }); var obj = new obj({ foo: null, bar: undefined, baz: 0, qux: "incorrect", }); obj.save(function(err, savedobj){ console.log(savedobj) // { foo: 10, bar: 10, baz: 10, qux: 10 } });
for more details might visit https://github.com/learnboost/mongoose/blob/master/lib/schematype.js#l250
Comments
Post a Comment