Michael Cole
Michael Cole

Reputation: 16207

Meteor collections. After altering schema, how to check for invalid documents? How to fix?

I'm using SimpleSchema and Collection2.

Before pushing a new version of my app, I'd like to check if any documents would be invalid with the new schema. Is there an automated way to do this?

Or a command line utility?

How do you release new versions with altered schemas?

Thanks!

Mike

Upvotes: 1

Views: 38

Answers (3)

Michael Cole
Michael Cole

Reputation: 16207

I followed @michel's advice and made this server-side route for checking collections.

This is pretty dangerous, because it's cleaning and saving your data. That means it's erasing fields. Probably you didn't want those fields which is why you removed them from your schema, but also, it may be a bug. So caveat emptor cowboy. Obviously, this shouldn't be on a production server.

They can be checked using an url like this:

http://127.0.0.1:4000/v/users

Response:

{
  "ok": 1
}

The route:

skipUpdatedAt = true;

Router.route('validate', {
  path: '/v/:collection',
  where: 'server',
  action: function() {

    var res = this.response;

    var collections = {
      users: Meteor.users,
      puppies: Puppies,
      unicorns: Unicorns,
      rainbows: Rainbows,
    };

    var c = collections[this.params.collection];
    if (!c) {
      res.statusCode = 404;
      return res.end('not found');
    }
    var s = c.simpleSchema();

    var ret = { ok: 0 };

    c.find().forEach(function(doc){
      var id = doc._id;
      try {
        s.clean(doc);
        check(doc,s);
        c.update(id, doc, {validate: false});
        ret.ok += 1;
      } catch (e) {
        ret[id] = {
          doc: doc,
          error: e.toString(),
        };
        console.log('=============ERROR');
        console.log(doc);
        console.log('-------------');
        console.log(e);
      }
    });

    res.statusCode = 200;
    if (Object.keys(ret).length) res.statusCode = 500;
    res.end(JSON.stringify(ret, null, 2));
  }
});

Upvotes: 0

Michel Floyd
Michel Floyd

Reputation: 20227

From your meteor app on either the client or server (assuming you have access to all the documents you want to check on the client):

MyCollection.find().forEach(function(doc){
  check(doc,MyCollectionSchema);
});

You'll probably also want to log the doc and its _id on failures so you can go fix them.

Upvotes: 2

mesosteros
mesosteros

Reputation: 1519

Both SimpleSchema and Collection2 have validating methods.

For SimpleSchema, here are their example codes: https://github.com/aldeed/meteor-simple-schema#validating-data

For Collection2, check the sections starting from Validation Contexts https://github.com/aldeed/meteor-collection2#validation-contexts

Upvotes: 0

Related Questions