Meteor transform Meteor.user and collections


#1

After reading a bit about models in [David Weldon’s blog][1] I see sense in using this kind of convention. My only problem is implementation. I cannot get this to work even for the simplest of collections.

I have this:

var region = {
    canInsert: function () {
       return false;
    }

};

Regions = new Mongo.Collection("regions", {
    transform: function (doc) {
        var newInstance = Object.create(region);
        return  _.extend(newInstance, doc);
    }
});




KM.Schemas = KM.Schemas || {};
KM.Schemas.regionSchema = new SimpleSchema({

    regionTitle: {
        type: String,
        label: "Region",
        max: 100
    },
    regionCode: {
        type: String,
        label: "Region Code",
        max: 10
    },
    focalPoint: {
        type: String,
        label: "Focal Point",
        max: 100
    },
    contactEmail: {
        type: String,
        label: "Email",
        max: 500,
        regEx: SimpleSchema.RegEx.Email
    },
    "contactEmail.$.address": {
        type: String,
        regEx: SimpleSchema.RegEx.Email
    },
    "contactEmail.$.verified": {
        type: Boolean
    }
})

Regions.attachSchema(KM.Schemas.regionSchema);

When I test by running console.log(Regions.canInsert); I get undefined. What am I doing wrong?

I would also like to have the same funtionality for Meteor.users where I can simply check user.isSuperAdmin. isSuperAdmin can take an array of roles which might need to be changed at any time hence the need for one function checking for superAdmin.

The canInsert parameter would check user.isSuperAdmin which for now I can’t execute because I haven’t quite wrapped my head around transforms.

Any guidance on these?
[1]: https://dweldon.silvrback.com/models


#2

The important takeaway from the collection transform documentation is this:

Documents will be passed through this function before being returned from fetch or findOne, and before being passed to callbacks of observe, map, forEach, allow, and deny. Transforms are not applied for the callbacks of observeChanges or to cursors returned from publish functions.

In other words this doesn’t add anything to your collection, it just changes what happens when each document is fetched.


#3

Regions.canInsert implies you’re trying to use the method as a “class-level” function, which is not the case

canInsert would be available as an instance method of your documents:

var region = Regions.findOne(); region.canInsert();

on another note, I’d rename region to Region for the sake of convention

as for the Meteor.users collection, I personally use the internal _transform property, since Meteor.users is not defined by the project developer:

Meteor.users._transform = function() { ... }