Using Meteor models?


#1

I’m new to Meteor and coming from Rails/Python background, already I am confused with how to organize my code. Suppose I have a bunch of models, things like User, List, Task, etc. Instead of a bunch of helpers and throwing the HTML templates into app.html, is there a more organized approach where each model gets its own .js / .jsx file?

I have looked into using React but can’t find more than a most basic Meteor/React example.


#2

Welcome @pickhardt !

Models are a bit tricky in Meteor because there isn’t a go-to ORM. I’ve rolled my own like this example. The concept is to share them on both the client and server. The client uses it to run it’s ‘simulation’ or ‘stub’ and the server copy does the real mutation.

For general app layout checkout my React-ive Meteor repo to see how you can organize your Blaze or React components/pages.

I would recommend reading this article to get the hang of template level subscriptions. It was very common to do this in the router and now the best practice is generally to let the template/component take care of it:
https://www.discovermeteor.com/blog/template-level-subscriptions/

I also just posted a new way to structure user actions and data manipulation, it might be worth reading as well (this will be rolled into React-ive Meteor in the next few days):

The nice thing is that Meteor lets you structure you app how you like. The bad part is that it takes a while to figure out what works best :smile:


#3

Using local packages is a great way to organise your code, I’ve found.

This way you can also modularise your project, specify load ordering and create re-usable parts for future apps.

http://docs.meteor.com/#/full/structuringyourapp (Check out Method 3)
Is packages-for-everything the solution to all Meteor problems?
A package-based starter template for Meteor apps

Additionally, you can specify mobile-only code this way.
http://docs.meteor.com/#/full/pack_addFiles


#4

I have been creating EJSON custom types for my models. It has been really useful and has allowed for some pretty clean code. You can create all the methods you want and make them run on the server or client or both. Here is an example:

// models/userModel.js

EJSON.addType("UserModel", function fromJSONValue(value) {
    return new UserModel(value);
});

// Constructor, gets used in transform function.
UserModel = function(doc) {
    this.pendingUpdates = [];
    _.extend(this, doc);
};

UserModel.prototype = {

    constructor: UserModel,

    //
    // EJSON Ovverrides.
    //
    valueOf: function() {
        return JSON.parse(JSON.stringify(this), function(key, value) {
            var dateFields = ["expiration", "createdAt"];
            if(_.contains(dateFields, key) && typeof value === "string") {
                return new Date(value);
            } else {
                return value;
            }
        });
    },

    typeName: function() {
        return 'UserModel';
    },

    toJSONValue: function() {
        return this.valueOf();
    },

    clone: function() {
        return new UserModel(this.valueOf());
    },

    equals: function(other) {
        if(!(other instanceof UserModel)) {
            return false;
        }
        return this._id === other._id;
    },
   // example setter
    setProfileFirstname: function(firstname, queueUpdate){
        var modifier = {$set: {'profile.firstname': firstname}};
        this.profile.firstname = firstname;
        return Meteor.users.findOne({_id:this._id},  modifier);
    },
    // sample getter
    getUsername:function(){return this.username;}
}

Then you can do something like.

var user = Meteor.user();
user.setFirstName("kris");  // sets first name to "kris"
user.getUsername();         // gets username (e.g. 'khamoud')

#5

There is no consensus in Meteor-land yet.

Along with the other suggestions, there are packages that I’ve used that attempt to address this problem. I’ve tried:

  • minimongoid - If you’ve used the mongoid gem, this might look familiar. It’s nowhere near the capability of mongoid, but it was making good progress when activity slowed down. Might not be a good bet because it’s not very active.

  • Combination of collection-helpers and collection-hooks - You can get model-like behavior in your collections by using these packages. This is my preferred approach at the moment.

  • astronomy - Astronomy recently surfaced and looks to be very comprehensive and promising.

HTH!


#6

ah your post is the bomb, with the explanations and links. Spent a good few hours looking through your material. thanks :slight_smile: