LearnBoost/mongoose — Issue #745: There are no way to force a value with validation?
Author: heycalmdown
Created: 2012-02-23 04:48:29+00:00
State: open

Here is my problem and approaches I tried. Anybody could give me an advice?

Think I have an object looks like this already:

```javascript
var MySchema = new mongoose.Schema({
already: {
I: {
had: String
}
}
});

>> {
already: { I: { had: "zero" }}
}
```

And then I change the schema has a Number instead of a String. So the object in the database has a String yet and new object I will make later would have a Number. When I get the old object using new schema, there is a string in the place I expect which has a number at this time. And it will occur an error when I try to re-save it. Right? But the way I really expecting is forcing the old value with newer.

So I could try this approach:

```javascript
var MySchema = new mongoose.Schema({
already: {
I: {
had: {type:Number, require:true, default:0}
}
}
});
```

I thought the combination of required and default option will force the old value to have a proper value if the value couldn't pass the validation check. Because there is a value that can't pass through its validation means that doesn't exists in the logical way, so the default option can be used. However it doesn't work. OK. I see. The options like require and default works when it saved. Not fetching time.

Second option. Using getter function.

```javascript
var MySchema = new mongoose.Schema({
already: {
I: {
had: {type:Number, require:true, default:0, min:0, get: forceWithValidation},
and: {type:Number, require:true, default:1, min:1, get: forceWithValidation}
}
}
});
```

I added some options and new variable. Actually I really can use getters. If an original value can't pass a validation for it, getter returns a proper value.

```javascript
function forceWithValidation(value) {
if (typeof(value) !== 'number') return 0;
return value;
}
```

But for better design, this function need to be able to dealing with several value have different validation options like above. It would be nice the function can access min/max options for Number.

If you have another better way, please let me know.