scottwrobinson / camo

A class-based ES6 ODM for Mongo-like databases.
556 stars 80 forks source link

Missing scheme validation on update #25

Open ijsf opened 8 years ago

ijsf commented 8 years ago

I am currently having an issue with the model/scheme validation in case of a loadOneAndUpdate call.

Specifically, consider the normal create function, as in camo's examples, which obviously validates the input. I've added a quite strict model as well:

class Dog extends camo.Document {
    constructor() {
        super('dogs');
        this.name = { type: String; required: true; };
        this.breed = { type: String; choices: [ 'Collie', 'Bulldog' ] };
    }
}

var lassie = Dog.create({
    name: 'Lassie',
    breed: 'Collie'
});

lassie.save().then(function(l) {
    console.log(l.id);
});

However, let's say I want to update the breed of a specified Dog entry. In this case, I would use the loadOneAndUpdate function since I want the other values to remain the same, and the create function obviously wouldn't work because of the missing name:

Dog.loadOneAndUpdate({ id: ... }, { breed: 'totallywrongvalue' }).then(function(l) { ... });

Note that the breed does not adhere to the model here. Yet, the document is actually updated with this invalid value.

To solve this issue, I guess loadOneAndUpdate would have to do some kind of validation. Perhaps additionally, an explicit validation function validate could be used and exposed which validates any given data against the model.

ijsf commented 8 years ago

Just noticed that a validate function does exist, though I guess a similar function that wouldn't check for missing keys would be more useful.

scottwrobinson commented 8 years ago

Hmm ya it looks like the internal validation isn't called when using loadOneAndUpdate. Nice catch. I'll include this fix in the upcoming update.

Thanks!