Matt
Matt

Reputation: 2821

In Mongoose, what value do I pass in for object property to get the default value from the schema?

In MongooseJS, I'm trying to create a new instance of a model based on POST data. In some cases I want a field to have the default value as defined on the schema, but when I pass in null or undefined for the value of that property, I'm not getting the default in the resulting Mongo object (I only get the default when I don't pass in the property at 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 that `baz` is 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 to have to write separate object instantiation code for each potential permutation of properties that might not have values, is there something I can set foo and bar too that will result in the default value? This seems like it should be a common case to me, but maybe I'm just missing something?

Upvotes: 2

Views: 588

Answers (1)

efkan
efkan

Reputation: 13217

I think, you should add a setter to your schema like the below. But it works only when you add a new record. When you update your documents it doesn't work. I hope it 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 you might visit to https://github.com/LearnBoost/mongoose/blob/master/lib/schematype.js#L250

Upvotes: 1

Related Questions