meteor-collection-hooks
meteor-collection-hooks copied to clipboard
Execution order of meteor-collection-hook and simple-schema validation is different on the server and the client
I am using collection2, simple-schema and meteor-collection-hooks.
First test
// posts.js
Posts = new Mongo.Collection("posts");
Posts.before.insert((userId, doc) => {
console.log('Should see this');
});
////////////////////////////////////////////////////////////////
// Then in meteor shell:
Posts.insert({title: 'some title'}); // I see the message in the server console. And a new Posts is inserted in mongo
Second test
// posts.js
Posts = new Mongo.Collection("posts");
Posts.attachSchema(new SimpleSchema({
title: {
type: String,
},
slug: {
type: String,
}
}));
Posts.before.insert((userId, doc) => {
console.log('POSTS BEFORE INSERT');
doc.createdAt = Date.now();
doc.slug = 'whatever';
});
Posts.allow({
insert: function() {return true},
update: function() {return true},
remove: function() {return true}
});
////////////////////////////////////////////////////////////////
// Then in meteor shell:
Posts.insert({title: 'some title'}); // validation error. No console.log. No Post inserted.
//
// Error: Slug is required
// at getErrorObject (packages/aldeed_collection2/packages/aldeed_collection2.js:425:1)
// at [object Object].doValidate (packages/aldeed_collection2/packages/aldeed_collection2.js:408:1)
//
////////////////////////////////////////////////////////////////
// In the chrome console:
Posts.insert({title: 'some title'}); // works just fine. I have a post with a title, slug and created_at
In the second case, the validation is run before the hook, so the Post is invalid and the hook is not executed at all (it needs to first pass through the hook to be valid).
Interestingly, I have not this problem while on the client. On the client, the execution order seems valid: hook THEN validation.
Do you have the same behavior ? Any idea why the order is different on the server?
I've noticed this behavior as well
Are there any workarounds, except disabling validation on server side?
Anyone ever find a workaround to this?
same here, it would be great to be able to run a hook before validation on the server to generate required computed properties
+1 this issue is very annoying!
Beware that, with this behavior, defaultValue is also applied on the server before the hook. So if you're checking for an undefined value, it will pass the test on the client, not on the server. I almost became crazy, but finally made the link with this issue...
I believe this issue might be related to this, hooks are attached to different things on server and client and that might be what's causing this problem.
Has anyone found a workaround that doesn't involve using defaultValues or validate: false on insert?