Execution order of meteor-collection-hook and simple-schema validation is different on the server and the client

219 Views Asked by At

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

////////////////////////////////////////////////////////////////
// Works fine both in meteor shell and console:
Posts.insert({title: 'some title'});

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 my second test in meteor shell, 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?


A workaround is to do this on the server:

Posts.insert({title: 'some title'}, {validate: false});

But I loose the validation, which I would like to keep...

See Github issue

0

There are 0 best solutions below