Code Monkey home page Code Monkey logo

meteor-collection-helpers's Introduction

Meteor Collection Helpers

Collection helpers automatically sets up a transformation on your collections using Meteor's Mongo.Collection transform option, allowing for simple models with an interface that's similar to template helpers.

Installation

$ meteor add dburles:collection-helpers

Usage

Write your helpers somewhere seen by both client and server.

Books = new Mongo.Collection('books');
Authors = new Mongo.Collection('authors');

Books.helpers({
  author() {
    return Authors.findOne(this.authorId);
  }
});

Authors.helpers({
  fullName() {
    return `${this.firstName} ${this.lastName}`;
  },
  books() {
    return Books.find({ authorId: this._id });
  }
});

This will then allow you to do:

Books.findOne().author().firstName; // Charles
Books.findOne().author().fullName(); // Charles Darwin
Authors.findOne().books()

Our relationships are resolved by the collection helper, avoiding unnecessary template helpers. So we can simply write:

Template.books.helpers({
  books() {
    return Books.find();
  }
});

...with the corresponding template:

<template name="books">
  <ul>
    {{#each books}}
      <li>{{name}} by {{author.fullName}}</li>
    {{/each}}
  </ul>
</template>

Meteor.users

You can also apply helpers to the Meteor.users collection

Meteor.users.helpers({
  // ...
});

Applying the transformation function

Sometimes it may be useful to apply the transformation directly to an object.

var doc = {
  firstName: 'Charles',
  lastName: 'Darwin'
};

var transformedDoc = Authors._transform(doc);

transformedDoc.fullName(); // Charles Darwin

License

MIT

meteor-collection-helpers's People

Contributors

dburles avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

meteor-collection-helpers's Issues

Reactive property

Hello,
I am trying to use your package to add property (and methods) to a collection.
I managed to add local property (not persisted in database) with :

Budget.helpers({
  show: true,
  toggleShow: function() {
    //console.log(this);
    this.show = !this.show;
    return this.show;
  }
});

In .html :

{{show}} // show always true
 <button id=#triggerShow></button> // call the this.toggleShow() in a event handler

It works, I have the property in the object and the method in the prototype of the objects.
However it did not update the value in the view (HTML) when I trigger the method. I would like to know what I did wrong or if it is possible at all ?

Infinite digest loop (infdig) with find() in helper

Not sure if this is an angular-meteor issue or an issue with the helpers, but i'm getting infinite loop warnings when trying to use find() in a helper method. This is my model:

Groups = new Mongo.Collection("groups");
Groups.helpers({
    usersByScore: function () {
        return Meteor.users.find({_id: {$in: this.users}}, {sort: {score: -1}});
    }
});
Groups.allow({
    insert: function (userId, group) {
        return Roles.userIsInRole(userId, 'admin');
    },
    update: function (userId, group, fields, modifier) {
        return Roles.userIsInRole(userId, 'admin');
    },
    remove: function (userId, group) {
        return Roles.userIsInRole(userId, 'admin');
    }
});

Publish:

Meteor.publishComposite("groupsForUser", function () {
    return {
        find: function() {
            return Groups.find({users: { $elemMatch: { $eq: this.userId}}});
        },
        children: [
            {
                find: function(group) {
                    return Meteor.users.find({_id: {$in: group.users}});
                }
            }
        ]
    };
});

controller:

angular.module('app').controller('ScoresController', ['$scope', '$meteor',
    function($scope, $meteor){
        $scope.groups = $meteor.collection(Groups).subscribe('groupsForUser');
    }
]);

view:

<md-tabs md-dynamic-height md-border-bottom>
    <md-tab label="{{ group.name }}" ng-repeat="group in groups">
        <md-content class="md-padding">
            <md-list>
                <md-list-item class="md-3-line" ng-repeat="user in group.userList()">
                    <span>{{ user.emails[0].address }} ({{ user.score }})</span>
                </md-list-item>
                <md-divider></md-divider>
            </md-list>
        </md-content>
    </md-tab>
</md-tabs>

There is only one group in the database with 2 users attached to the group. The exact error is:

Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: [[{"msg":"fn: regularInterceptedExpression","newVal":29,"oldVal":26}],[{"msg":"fn: regularInterceptedExpression","newVal":32,"oldVal":29}],[{"msg":"fn: regularInterceptedExpression","newVal":35,"oldVal":32}],[{"msg":"fn: regularInterceptedExpression","newVal":38,"oldVal":35}],[{"msg":"fn: regularInterceptedExpression","newVal":41,"oldVal":38}]]
http://errors.angularjs.org/1.4.2/$rootScope/infdig?p0=10&p1=%5B%5B%7B%22ms…rInterceptedExpression%22%2C%22newVal%22%3A41%2C%22oldVal%22%3A38%7D%5D%5D
at REGEX_STRING_REGEXP (angular.js:68)
at Scope.$get.Scope.$digest (angular.js:15723)
at Scope.$get.Scope.$apply (angular.js:15953)
at safeApply (angular-meteor-meteorCollection.js:154)
at Object.angularMeteorCollections.factory.AngularMeteorCollection.updateCursor.self.observeHandle.cursor.observe.addedAt (angular-meteor-meteorCollection.js:174)
at LocalCollection._observeFromObserveChanges.observeChangesCallbacks.addedBefore (observe.js:96)
at Object.LocalCollection._CachingChangeObserver.self.applyChange.addedBefore (observe.js:33)
at minimongo.js:373
at _.extend.runTask (fiber_stubs_client.js:42)
at _.extend.flush (fiber_stubs_client.js:70)

Exception in queued task: Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: [[{"msg":"fn: regularInterceptedExpression","newVal":29,"oldVal":26}],[{"msg":"fn: regularInterceptedExpression","newVal":32,"oldVal":29}],[{"msg":"fn: regularInterceptedExpression","newVal":35,"oldVal":32}],[{"msg":"fn: regularInterceptedExpression","newVal":38,"oldVal":35}],[{"msg":"fn: regularInterceptedExpression","newVal":41,"oldVal":38}]]
http://errors.angularjs.org/1.4.2/$rootScope/infdig?p0=10&p1=%5B%5B%7B%22ms…rInterceptedExpression%22%2C%22newVal%22%3A41%2C%22oldVal%22%3A38%7D%5D%5D
at REGEX_STRING_REGEXP (http://localhost:3000/packages/angular_angular.js?c3a778493846e58a63e652cd68b47914889a794c:98:12)
at Scope.$get.Scope.$digest (http://localhost:3000/packages/angular_angular.js?c3a778493846e58a63e652cd68b47914889a794c:15753:19)
at Scope.$get.Scope.$apply (http://localhost:3000/packages/angular_angular.js?c3a778493846e58a63e652cd68b47914889a794c:15983:24)
at safeApply (http://localhost:3000/packages/urigo_angular.js?3cfbb5ec69330c7589d9a07bff661ca2dd28d04d:1173:47)
at Object.angularMeteorCollections.factory.AngularMeteorCollection.updateCursor.self.observeHandle.cursor.observe.addedAt (http://localhost:3000/packages/urigo_angular.js?3cfbb5ec69330c7589d9a07bff661ca2dd28d04d:1193:11)
at LocalCollection._observeFromObserveChanges.observeChangesCallbacks.addedBefore (http://localhost:3000/packages/minimongo.js?af9eb9d7447544ca9b839a3dcf7ed2da2209b56c:3862:28)
at Object.LocalCollection._CachingChangeObserver.self.applyChange.addedBefore (http://localhost:3000/packages/minimongo.js?af9eb9d7447544ca9b839a3dcf7ed2da2209b56c:3799:56)
at http://localhost:3000/packages/minimongo.js?af9eb9d7447544ca9b839a3dcf7ed2da2209b56c:415:13
at _.extend.runTask (http://localhost:3000/packages/meteor.js?43b7958c1598803e94014f27f5f622b0bddc0aaf:693:11)
at _.extend.flush (http://localhost:3000/packages/meteor.js?43b7958c1598803e94014f27f5f622b0bddc0aaf:721:10)

Can't use collection helper on FS.Collection.

Say Photos is a FS.Collection. And when you do Photos.files.helpers({...}); you get Error: [Can't apply helpers to 'cfs.photos.filerecord' a transform function already exists!] error message. CollectionFS doc says underlying Mongo.Collection instance available through myFSCollection.files.

Big data

Hello! Thanks for this package!

I have big data (~100000 documents). I publish first 100 and then +100 on every request.

Documents have relations with other collections. I use helpers like this

City.helpers
    countryObj: ->
        Country.findOne({_id: this.country}) 

So I publish 100 items and list related fields in table ({{ countryObj.title }}). It is empty, because I published few of them (of ~100000). When I request next part empty fields get data ...

Is it possible load related fields without waiting?

Question about scope of "this"

Hey @dburles how are you doing?
Can you help me in a question that is more Javascript related?
I'm using meteor reactive table: https://github.com/ecohealthalliance/reactive-table
to render a bunch of data in a table and the author created Handlebars helper that render those things.
To get fields of the document on the template, he does this:

Template.reactiveTable.helpers({
    "getField": function (object) {
        var fn = this.fn || function (value) { return value; };
        var key = this.key || this;
        var keys = key.split('.');
        var value = object;
        _.each(keys, function (key) {
            if (!_.isUndefined(value) && !_.isUndefined(value[key])) {
                value = value[key];
            } else {
                value = null;
            }
        });
        var computedValue = fn(value, object);
        return computedValue;
    },
...
            {{#each ../fields}}
                <td class="{{key}}">{{getField ../this}}</td>
            {{/each}}

I've forked his project to use with yours and changed the last lines of that function to this:

        var computedValue = fn(value, object);
        if (typeof computedValue === 'function') {
          return computedValue(); 
        }
        return computedValue;
    },

Then I created a helper for my collection:

if (Meteor.isClient) {
  Hotspot.helpers({
    virtualEstablishment: function () {
      var establishment = Establishment.findOne(this.establishment);
      console.log(this, establishment)
      return establishment; 
    }
  });
}

When I log "this" keyword, it's the scope of the window, not the document.
Do you know why and could you please help me understanding this?

server -> client support?

Thanks again for a great package, i'm using it for a number of things.

I am using a Meteor.call() to create/lookup an object on the server, and then return a cursor to the client.
however the object comes back with no collectionHelper methods attached. in fact it seems to have prototype of Object.

doing a findOne() client side returns a collectionHelper-ified object.

Is there a way to send these type of objects over the wire from Meteor.call methods?
Or is there a way to re-transform the collection helper methods to a raw Object?

image

Thanks!

Collection.allow

In my Collection.allow method I'm adding a userId (see code below). When I add helpers to that collection, that stops working. Any idea?

// /both/collections/cases.js
Cases.allow({
  insert: function (userId, doc) {
    doc.userId = userId;
    return !! userId;
  }
});

Allow helpers with find(), not only findOne()

Would it be possible to use helpers with find() ?

The reason to do that, in my case, is that I need to transform the results of find() into an array I can feed into a select input, grabbing the id and a name.

That was the first thing I tried to do with meteor-collection-helpers, and it didn't work, then I realized all the examples used findOne(). If it doesn't make sense, maybe the docs could mention that the helper is available via findOne() only.

Performance collection-helpers vs denormalization

Is there any difference regarding performance? I think mongo would be happy if it doesn't need to store duplicates. But how does it look like regarding reactivity and only publishing certain fields?

Big thanks :)

Meteor.user helpers with extra fields

Hello, my Meteor.users is something like this:

{
username: {}
services: {}
profile: {}
>>> info <<< : {}
}

I have this extra field called info where I store important things about the user
when using a helper in Meteor.users, the object "this" does not have the "Info" field, only username, services, profile...
How can I solve this ?

Create an object not attached to a collection?

If I set helpers for a collection, then on each call to colliection like findOne, etc I will obtain an object with these helpers set. However, I do not see any way to create a similar object without a call to a collection.

For example, if I follow the approach from Meteor documentation:

Animal = function (doc) {
  _.extend(this, doc);
};
_.extend(Animal.prototype, {
  makeNoise: function () {
    console.log(this.sound);
  }
});

// Define a Collection that uses Animal as its document
Animals = new Mongo.Collection("Animals", {
  transform: function (doc) { return new Animal(doc); }
});

// Create an Animal and call its makeNoise method
Animals.insert({name: "raptor", sound: "roar"});
Animals.findOne({name: "raptor"}).makeNoise(); // prints "roar"

then I can use something like

var an = new Animal({"sound" : "aaa"});
an.makeNoise();

without any need to have any entries in a collection, etc. Is this possible, or can this be done possible with collection-helpers?

(Actual my issue is that in a test code, I would like to create an object and test its methods without having a collection.)

How to write tests using collection helpers?

Hi there, I'm coming from Ruby on Rails.
collection helpers are really similar idea with RoR's active models. it's very convenient to write complex data operations into one same place.

however, I'm trying to write test code using jasmine or other meteor test framework, such as MUnit, Tinytest, and gagarin, but I can't be achieved.

For example, collection A has many related collection B's records and I centralize the creation of B's record in the collection A's helper, I can write:

A = new Mongo.Collection('a');
B = new Mongo.Collection('b');
A.helpers({
  createB: function(params) {
    params.parent = this._id;
    return B.insert(params);
  },
  listB: function() {
    return B.find({parent: this._id});
  }
});

This case, I should write test like:

describe('A', function() {
  var a1;
  beforeAll(function() {
    a1 = A.insert({name: 'first A'});
  }
  it('shoud have many Bs', function() {
    expect(a1.listB.count()).toBe(0);
    a1.createB({name: 'b1'});
    expect(a1.listB.count()).toBe(1);
  }
}

helpers included in find?

[feature request]
is it possible to extend these to work with mongoDB finds?

eg from this example:

Books.helpers({
  author: function() {
    return Authors.findOne(this.authorId);
  }
});

bk = Books.find({ author: 'tom' })

Idea: access parent cursor in doc helpers

That would be pretty useful to be able to access the parent cursor from a document returned to the helpers method, and in particuler its previous / next docs in the cursor.

That would make things like grouping elements by an attribute very clean. Examples: for a chat app where you would need to insert a separator for each day, a contacts list where you need to group people by the first letter of their names, etc.

The code could look like this:

Messages.helpers({
  '$newDay': funtion(prev, next) {
    return (!prev || (this.day !== prev.day)) ? this.day : null;
  }
});

Haven't been able to dig into minimongo yet - but @dburles do you think this is something that can be done?

custom helper keeps returning same document

I'm using meteor-admin combined with meteor-collection-helpers to try and display a custom helper within the 'view all' view of my collection.

I have two collections; artists and artistImages. artistImages are linked to an artists with their _id. That works fine and I have the correct artists name displaying in my dropdown in the edit/new screen of artistImages. I want the artist's name to display in the 'view all' section of the artistImages collection against each row, but for some reason its always the first artists name which displays.

In my meteor-admin config file I have the collection setup like this:

...
ArtistImages: {
    tableColumns: [
        { label: 'ArtistId', name: 'artistId' },
        { label: 'Artist', name: function() {
                return ArtistImages.findOne().artist();
            }
        },
        { label: 'Image', name: 'image' },
    ]
},
...

Then inside my artistImages collection definition I have

ArtistImages = new Mongo.Collection("artist-images");

ArtistImages.helpers({
    artist: function() {
        var artist = Artists.findOne(this.artistId);
        if(artist){
            return artist.name;
        } else {
            return "(undefined)";
        }
    }
});

Schemas = {};

Schemas.ArtistImages = new SimpleSchema({
    artistId: {
        type: String,
        label: 'Artist',
        autoform: {
            options: function () {
                return _.map(Artists.find({}).fetch(), function (artist) {
                    return {
                        label: artist.name,
                        value: artist._id
                    };
                });
            }
        }
    },
    image: {
        type: String,
        label: 'Image',
        max: 200,
        optional: true
    },
    caption: {
        type: String,
        label: 'Caption',
        max: 120,
        optional: true
    }
});

ArtistImages.attachSchema(Schemas.ArtistImages);

However if i console.log this.artistId from within the artist() helper, its always returning the same id even if i have different artists assigned to each artist image.

view all:

screen shot 2015-11-21 at 1 58 59 pm

Notice the artistId is different but the name is the same, both names are for the artist in the first row.

Any suggestions? I'm stumped.

Working with collection2

I am using simple schema (aldeed:simple-schema) and collection2 (aldeed:collection2) in my app, i wish to know if this will work seamlessly with both before trying

Helper to all collections

Hi! all my collections have a field called createdBy
I would like to create a helper to all my collections to retrieve the user that createdBy is referring to
Can I achieve this with collection-helpers package?

helpers in document on allow

The meteor collection methods to allow and deny objects on update and remove give a parameter doc which contains the original object before modification. These do not have the helpers attached. Is that fixable?

postCreate hooks?

i understand this package was designed to be lightweight, but is there any support for common lifecycle events? eg onCreate onDestroy etc? for validation or other setup tasks for new objects?

or do you recommend another package in combination, and if so which?

How to return a reactive cursor?

So I'm trying to return a cursor

Posts.helpers (->
   comments: ->
     Comments.find belongsToPost: @_id
)

Then I call this helper from Template.onCreated: Posts.comments() and it does indeed return a cursor. Kind of. Because I can't do anything with the cursor, for example I can't do Posts.comments().find(belongsToPost: 12)

So is it possible to return a functional cursor? And more important, is that cursor reactive?

Collection helpers not working with Jasmine test environment

It seems that in Jasmine test environment, if I set helpers for several collections, some helpers are lost.

I have created a test repository: https://github.com/petr-kalinin/meteor-collection-name-missing . If you clone it and start Meteor, you will see in browser's console the output like

collection-helpers: collection name: foo
collection-helpers: collection name: bar
Foo name: foo
Bar name: bar
Foo whoami: Foo
Foo foo: Foo:foo
Bar whoami: Bar
Bar bar: Bar::bar

which is the expected output.

However, the (only) test is not passed. Moreover, if you start Meteor with
DEBUG=1 JASMINE_DEBUG=1 VELOCITY_DEBUG=1 VELOCITY_DEBUG_MIRROR=1 meteor
and, after the startup, change the test file to have tests rerun, you will see in the terminal the following output:

I20150327-22:30:50.705(3)? [sanjo:jasmine]: loading source file: /home/petr/meteor-univ/jasmine-collection-name/lib/dburles:collection-helpers.js
I20150327-22:30:50.708(3)? [sanjo:jasmine]: loading source file: /home/petr/meteor-univ/jasmine-collection-name/collections/foobar.coffee
I20150327-22:30:50.750(3)? collection-helpers: collection name: undefined
I20150327-22:30:50.750(3)? collection-helpers: collection name: undefined
I20150327-22:30:50.750(3)? Foo name: undefined
I20150327-22:30:50.750(3)? Bar name: undefined
I20150327-22:30:50.751(3)? Foo whoami: Bar
W20150327-22:30:50.752(3)? (STDERR) [sanjo:jasmine]: The code has syntax errors. [TypeError: Object [object Object] has no method 'foo']

which is not the expected output, the output identical to the one in the browser console is expected.

I have added a debug output into dburles:collection-helpers.js file (see in the repository), and it seems that in normal run, the _name field of a collection is set properly, while in Jasmine it is undefined for every collection. As a result, all collections share the same element in Document array, which leads to this strange behavior. In particular in my case, Foo helpers are simply overwritten by Bar helpers.

I do not know whether this is a problem of this package, or of Jasmin and/or Velocity.

(A separate issue is that I had to copy the dburles:collection-helpers.js file from package to the local lib directory not only to add debug output, but also to have Jasmine even see it.)

Why not transform?

Great package!

I wanted to ask you if there is any specific reason for not using the transform method to apply those helpers. I had a lot of problems when trying to inherit data because functions are not inherited through template instances.

Consider using Shadow Collection?

I love this package but it had a few issues and think I have build a solution to them with: https://github.com/Meteor-Reaction/shadow-collection.

What you would get to using this:

  • non-conflict - other packages that want to proved helpers can do so without conflicting with this package.
  • it lets Mongo.Collection transform work again
  • It removes the console reference to Mongo.Collection.helpers.Document.(anonymous function)

If this interests you I would be happy to do a PR, or leave it to you.

_ is not defined

I am experiencing an odd issue where underscore is not defined. I see that someone else had this issue and you added underscore to the API.use() oddly enough I am not getting this error on new projects that I import my core on?

W20150616-09:33:43.507(-4)? (STDERR) ReferenceError: _ is not defined
W20150616-09:33:43.508(-4)? (STDERR)     at [object Object].Meteor.Collection.helpers (packages/dburles:collection-helpers/collection-helpers.js:17:1)
W20150616-09:33:43.508(-4)? (STDERR)     at packages/bace:core/lib/both/collections/projects.collection.js:180:1
W20150616-09:33:43.509(-4)? (STDERR)     at /Users/patricklewis/Documents/sites/meteor/baceadmin/.meteor/local/build/programs/server/packages/bace_core.js:642:4
W20150616-09:33:43.509(-4)? (STDERR)     at /Users/patricklewis/Documents/sites/meteor/baceadmin/.meteor/local/build/programs/server/packages/bace_core.js:1467:3
W20150616-09:33:43.509(-4)? (STDERR)     at /Users/patricklewis/Documents/sites/meteor/baceadmin/.meteor/local/build/programs/server/boot.js:222:10
W20150616-09:33:43.510(-4)? (STDERR)     at Array.forEach (native)
W20150616-09:33:43.510(-4)? (STDERR)     at Function._.each._.forEach (/Users/patricklewis/.meteor/packages/meteor-tool/.1.1.3.1wysac9++os.osx.x86_64+web.browser+web.cordova/mt-os.osx.x86_64/dev_bundle/server-lib/node_modules/underscore/underscore.js:79:11)
W20150616-09:33:43.511(-4)? (STDERR)     at /Users/patricklewis/Documents/sites/meteor/baceadmin/.meteor/local/build/programs/server/boot.js:117:5

"Global" helpers on mongo collections

Excuse my inability in JavaScript, but I am wondering if there is a way to implement "global" helpers. It would be really nice, as I find myself repeating the same few helpers a lot. For example,

Meteor.users.helpers({
  fullName: function() {
    return firstName + " " + lastName;
  }
});

Players.helpers({
  fullName: function() {
    return firstName + " " + lastName;
  }
});

Ideally, it'd be nice to do something like this:

Mongo.Collection.helpers({
  fullName: function() {
    return firstName + " " + lastName;
  }
});

Is this possible?

Question: Nested Helpers

Consider the following snippets from https://github.com/aldeed/meteor-collection2#attach-a-schema-to-meteorusers

Schema.UserProfile = new SimpleSchema({
    //...
    firstName: {
        type: String,
        label: 'First name',
        denyUpdate: true,
    },
    lastName: {
        type: String,
        label: 'Last name',
        denyUpdate: true,
    },
    //...
});

Schema.User = new SimpleSchema({
    //...
    profile: {
        type: Schema.UserProfile,
        optional: true
    },
    //...
});

Meteor.users.attachSchema(Schema.User);

Is it possible to attach a nested fullName helper to user profiles, so that:

user.profile.fullName = user.profile.firstName + ' ' + user.profile.lastName

This was only an example, but when dealing with large complex object structures, one may like to group and nest helpers for organizational needs... Is this possible using this package?

Match.test issue

I think, though I am not certain, that this framework is causing problems with Match.test.

http://docs.meteor.com/#matchpatterns

For the object pattern, it says

The value must be a plain Object with no special prototype.

basically, I'm having an issue in Collection.allow

console.log doc.prototype says undefined.

This match fails:

match = Match.test doc,
  _id: String
  author: String
  createdAt: Number
  what: String
  down: [String]

But these matches dont fail:
console.log Match.test doc._id, String
console.log Match.test doc.author, String
console.log Match.test doc.createdAt, Number
console.log Match.test doc.what, String
console.log Match.test doc.down, [String]

I tries simply transposing the keys and this worked:
d =
_id: doc._id
author: doc.author
createdAt: doc.createdAt
what: doc.what
down: doc.down

match = Match.test d,
  _id: String
  author: String
  createdAt: Number
  what: String
  down: [String]

And I checked that there are no hidden keys:
console.log Object.keys(doc)

Anyways, I'm at a loss. This very well could be an entirely different issue...

Maximum Collection Supported

What is the maximum collection I can join together with this package? I have 6 collection which are referenced with each other. Can I used it?

Meteor.users.helpers not defined

Hi,

I'm trying to use this package to link to another document on the users collection.
Its throwing an error at the line 'Meteor.users.helpers({....});'
It does this on a freshly created meteor project version 1.0.3.2
Any ideas what it could be?

Thanks

Making helpers available to another collection?

The issue

I often mirror collections and I need collection helpers to be transferred from one collection to the other.

The solution that comes immediately to mind is:

MyCollectionB = new Mongo.Collection('myCollectionB', { transform: MyCollectionA._transform });

But this solution fails in the following use case:

MyCollectionA.helpers({
  next: function() {
    return MyCollectionA.findOne({ order: { $gt: this.order } }, { sort: { order: 1 } });
  }
});

Indeed, if I transfer this helper to MyCollectionB using the above solution, I get MyCollectionB::next() returning an item from MyCollectionA!

What I did to solve the issue

In collection-helpers.js, I have added the following line at the very end:

self._helpers.prototype.collection = function() { return self; };

Then I do this:

SharedHelpers = {
  next: function() {
    return this.collection().findOne({ order: { $gt: this.order } }, { sort: { order: 1} });
  }
};

MyCollectionA.helpers(SharedHelpers);
MyCollectionB.helpers(SharedHelpers);

Any advice on how to improve this?

Using with limit

If in collection more 100 docs then i using {limit: 25} (meteor-pages), and collection-helpers doesn`t work =/

Meteor Pages doesn't recognize the collection helpers

This has been an amazing plugin, extremely helpful to replicate some of the functionality from ember.js. It's mainly worked everywhere aside from Meteor Pages. For some reason, it doesn't detect the helpers for the specific collection, I wonder if this is because it looks directly at the collection or the transformed version of it with the helpers. Would this be an issue more related to the Meteor Pages package?

Helpers on the Server

Is there anything special I need to so on the server to get access the collection helpers?

Meteor.users.helpers
  checkContacts = (usernames) ->
    if _.difference(usernames, @contacts).length isnt 0
      throw new Meteor.Error(601, 'Not a contact!')

Meteor.methods
  addContacts: (contacts) ->
    user = Meteor.users.findOne(@userId)
    if user
      user.checkContacts cantacts

I'm not sure why this wouldnt work

Common Helpers

The method used in this package is great. I'm thinking of deprecating virtualFields support in collection2 and telling everyone to use this package instead. It's better because the methods are called only as necessary.

Anyway, I suggest an option to define common helpers more easily. Like this:

One = new Meteor.Collection('one');
Two = new Meteor.Collection('two');
Three = new Meteor.Collection('three');
Four = new Meteor.Collection('four');

CollectionHelpers.addHelpers({
  creator: function() {
    return Meteor.users.findOne(this.createdBy);
  }
}, [One, Two, Three, Four]);

In apps with many collections that share many common properties, this could simplify the code a lot.

Compatibility with check

Collection helpers seems to add a special prototype to documents, meaning a test like check(doc, Object) on a doc from a findOne call would unexpectedly fail. Is there a better way to do checking on documents besides explicitly checking individual keys?

ReferenceError: _ is not defined with coffescript

I've created a package which uses the collection-helpers package, but i'm getting some very indecipherable errors.

error is around _ not being defined inside collection-helpers*

Ensure dependencies...
W20140511-04:26:12.268(-7)? (STDERR) 
W20140511-04:26:12.268(-7)? (STDERR) /Users/dc/.meteor/tools/43b8566b9f/lib/node_modules/fibers/future.js:173
W20140511-04:26:12.269(-7)? (STDERR)                        throw(ex);
W20140511-04:26:12.269(-7)? (STDERR)                              ^
W20140511-04:26:12.273(-7)? (STDERR) ReferenceError: _ is not defined
W20140511-04:26:12.273(-7)? (STDERR)     at Meteor.Collection.helpers (packages/collection-helpers/collection-helpers.js:6)
W20140511-04:26:12.273(-7)? (STDERR)     at __coffeescriptShare (packages/bot/Chatbots.coffee:19:9)
W20140511-04:26:12.274(-7)? (STDERR)     at packages/bot.js:131:4
W20140511-04:26:12.274(-7)? (STDERR)     at packages/bot.js:191:3
W20140511-04:26:12.274(-7)? (STDERR)     at /Users/dc/dev/shumi/mechat/.meteor/local/build/programs/server/boot.js:155:10
W20140511-04:26:12.274(-7)? (STDERR)     at Array.forEach (native)
W20140511-04:26:12.274(-7)? (STDERR)     at Function._.each._.forEach (/Users/dc/.meteor/tools/43b8566b9f/lib/node_modules/underscore/underscore.js:79:11)
W20140511-04:26:12.275(-7)? (STDERR)     at /Users/dc/dev/shumi/mechat/.meteor/local/build/programs/server/boot.js:82:5
=> Exited with code: 8

I tried adding underscore even to my own package:

Package.on_use(function(api) {
    api.export(['Chatbots', 'Botrules']);   
    api.use(['coffeescript', 'underscore', 'collection-helpers']);
    api.add_files(['collections.coffee', 'Chatbots.coffee', 'Botrules.coffee', 'globals.js']);
});

I'm guessing this maybe something coffeescript related :(

following this issue
http://stackoverflow.com/questions/23281235/coffeescript-namespace-exports-in-meteor-custom-packages

I also tried using a separate globals.js

this is with meteor 0.8.1.1

have collection-helpers succesfully been used in other packages?
i guess the next thing is to rewrite everything in vanilla .js >.<

User helpers not available in Accounts.validateLoginAttempt(...)

Right now, I have to do the following:

Accounts.validateLoginAttempt(function(attempt) {
    var user = Meteor.users.findOne(attempt.user._id);
    console.log(user.fullName());
});

I would like to be able to do the following:

Accounts.validateLoginAttempt(function(attempt) {
    console.log(attempt.user.fullName());
});

Subsequent Helper Not Working

I have collections: As, Bs, Cs. And I've written helpers like so

As.helpers({
  bs: function () {
    return Bs.find(_id: {$in: this.bIDs}});
  }
});
Bs.helpers({
  cs: function () {
    return Cs.find(_id: {$in: this.cIDs}});
  }
});

And I have templates like so

<template name="AList">
{{#each as}}
  {{> ASingle}}
{{/each}}
</template>

<template name="ASingle">
A Name: {{name}}
{{> BList}}
</template>

<template name="BList">
{{#each bs}}
  {{> BSingle}}
{{/each}}
</template>

<template name="BSingle">
B Name: {{name}}
{{> CList}}
</template>

<template name="CList">
{{#each cs}}
  {{> CSingle}}
{{/each}}
</template>

<template name="CSingle">
C Name: {{name}}
</template>

On my HTML page, I see a list of all the As and their names with their nested Bs and their names.
But I do not see a list of the nested Cs within the B groups. I do see the text "C Name: " just once but there's nothing next to it.

Also, I have console log functions in the Bs helper to get cs and I don't see any log statements on server or client.

Am I trying to nest too many helpers? Is this even possible?

Issues it's not:

  • Publications, as I have Meteor Toys and can see the published Cs
  • Not associated with the parent B, as I've checked on the Mongo server

Conflict with tap-i18n-db collection

Hi, trying to use helper with tap-i18n-db collection and got this error:

Uncaught Error: [Can't apply helpers to 'meals' a transform function already exists!]

Any ways to make them compatible?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.