如何在更新集合中的文档之前验证SimpleSchema的更新

时间:2016-01-03 19:28:51

标签: meteor simple-schema atmosphere.js

我尝试在将SimpleSchema提交到集合之前验证我的数据,但由于某种原因,我无法解决此错误。

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

我有一个包含两个SimpleSchema的集合,如下所示。

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);

在用户创建供应商文档后,将添加vendorCategory。

这是我的客户端的样子。

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);
            }
        });
    }
});

这就是我的服务器端Meteor.methods的样子

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');
    }
}

我猜这是错误的来源。

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

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

由于您已经为子对象定义了子模式,因此可以直接检查:

check(vendorCategories,VendorCategoriesSchema)