Is There A Single Function/Method to Do Any Spefic Action With Any Specific Collection?


#1

I am fairly new to Meteor so please forgive me if this is a basic and/or stupid question. Each time I create a meteor app, I always end up having to write Collection.insert, .update, .upsert, etc for each collection that I am interacting with. I am looking for a way to have it as one call where I pass in the action, the collection, and the object with the action details.

For example, what I have working right now is being able to pass in the collection name and the object to be inserted and all of my Collection.insert functions are being called with it, along with my .find().

'collectionInsert': function(collection,insertObject){
  Mongo.Collection.get(collection).insert(insertObject);
}

However, I still have to say ".insert()’, so to update a collection, I would have to make a new function and call it collectionUpdate. Which isn’t that big of a deal but I would rather have one call that I make for every interaction with the collection and pass it parameters to figure out which collection, which action, and what data.

I’m sure there’s some solution that I’m overlooking/too novice to know. Anyone have any pointers to where I should look for the answer?


#2

If you attach your collections to a namespace object, you can use bracket notation, like so:

Collection["Foo"].upsert(newObject);

You’ll need to set them up beforehand though:

Collection = {};
Collection.Foo = new Collection('foo');
Collection.Baz = new Collection('baz');

#3

What I have that seems to be working on the limit testing I did of it is this:

'collectionInteraction': function(collection,action,actionObject){
    check(collection, String);
    check(action, String);
    check(actionObject, Object);

    switch(action){

        case 'update':
            Mongo.Collection.get(collection).update(actionObject);
            break;
        case 'insert':
            Mongo.Collection.get(collection).insert(actionObject);
            break;
        case 'upsert':
            Mongo.Collection.get(collection).upsert(actionObject);
            break;
        case 'remove':
            Mongo.Collection.get(collection).remove(actionObject);
            break;
        default:
            console.log("You put the wrong action in ya dingus");

    }

    return 1;
  }

And am currently calling it like this:

Meteor.call('collectionInteraction',collection,action,actionObject, function (error, result) {
      if(error){
        Bert.alert( 'There was an error: ' + error, 'danger', 'growl-top-right' );
      }else {
        Bert.alert( 'Hey we did it!', 'success', 'growl-top-right' );
      }
    });

I’m wanting all of my interaction with collections to be ran through one function so if there is any issues, I know exactly where they are. Basically creating an API for collection interaction that is on top of Meteor/Mongo’s API. If I’m using those words correctly…