Search code examples
meteorsimple-schemaatmosphere.js

How to validate an update against SimpleSchema before updating a document in collection


I'm trying to validate my data against a SimpleSchema before it gets submitted to the collection but for some reason I'm not able to do so with this error.

Exception while invoking method 'createVendorCategory' { stack: 'TypeError: Cannot call method \'simpleSchema\' of undefined

I have one collections with two SimpleSchemas as follows.

Vendors = new Mongo.Collection('vendors'); //Define the collection.

VendorCategoriesSchema = new SimpleSchema({
    name: {
        type: String,
        label: "Category"
    },
    slug: {
        type: String,
        label: "Slug"
    },
    createdAt : {
        type: Date,
        label: "Created At",
        autoValue: function(){
            return new Date()//return the current date timestamp to the schema
        }
    }
});

VendorSchema = new SimpleSchema({
    name: {
        type: String,
        label: "Name"
    },
    phone: {
        type: String,
        label: "Phone"
    },
    vendorCategories:{
        type: [VendorCategoriesSchema],
        optional: true
    }
});
Vendors.attachSchema(VendorSchema);

The vendorCategory will be added after the Vendor document is created by the user.

Here is what my client side looks like.

Template.addCategory.events({
    'click #app-vendor-category-submit': function(e,t){
        var category = {
            vendorID: Session.get("currentViewingVendor"),
            name: $.trim(t.find('#app-cat-name').value),
            slug: $.trim(t.find('#app-cat-slug').value),
        };

        Meteor.call('createVendorCategory', category, function(error) {
            //Server-side validation
            if (error) {
                alert(error);
            }
        });
    }
});

And here is what my server side Meteor.methods look like

createVendorCategory: function(category) 
{ 
    var vendorID =  Vendors.findOne(category.vendorID);
    if(!vendorID){
        throw new Meteor.Error(403, 'This Vendor is not found!');
    }
    //build the arr to be passed to collection
    var vendorCategories = {
        name: category.name,
        slug: category.slug
    }

    var isValid = check( vendorCategories, VendorSchema.vendorCategories.simpleSchema());//This is not working?
    if(isValid){
        Vendors.update(VendorID, vendorCategories);
        // return vendorReview;
        console.log(vendorCategories);
    }
    else{
        throw new Meteor.Error(403, 'Data is not valid');
    }
}

I'm guessing this is where the error is coming from.

var isValid = check( vendorCategories, VendorSchema.vendorCategories.simpleSchema());//This is not working?

Any help would be greatly appreciated.


Solution

  • Since you've already defined a sub-schema for the sub-object you can directly check against that:

    check(vendorCategories,VendorCategoriesSchema)