Giter Club home page Giter Club logo

meteor-collection-behaviours's Introduction

Mongo Collection Behaviours

Extends Mongo.Collection with custom behaviour patterns.

Uses the excellent collection-hooks package to hook into collection hooks.


Getting Started

Installation:

meteor add sewdn:collection-behaviours

.timestampable()

Adds the timestampable behaviour.

Every document inserted into the collection, will have a createdAt timestamp added to it. Every document of the collection that is being updated, will have a updatedAt timestamp added to it (or updated).

var test = new Mongo.Collection("test");

test.timestampable();

TODO

  • add options to choose the name of the createdAt and updateAt fields
  • add options to enable/disable createdAt, updatedAt timestamp

.autoIncrementable()

Adds an autoIncremented value.

Every document that gets inserted into the collection, will have a field added to it, containing a unique integer that is one (or other increment) higher than the previously inserted document.

var test = new Mongo.Collection("test");

test.autoIncrementable('fieldName', 2);

.softRemovable()

Adds the soft delete behaviour.

This behaviour is useful to keep track of removed documents. Every document that gets removed from the collection, will not really be removed, but a removed boolean and a removedAt timestamp will be added. Documents that are searched in the collection, will not be found if they have been indicated as being removed.

var test = new Mongo.Collection("test");

test.softRemovable();

TODO

  • add options to choose the name of the removed and removedAt fields

.sortable()

Adds the sortable pattern.

This pattern is useful to add a default sorting to a collection, other than insertion order. This behaviour uses the autoIncrement behaviour to add a field with an integer value. Extra methods are added to the prototype of the transformed document to change the position in the sorted list.

var test = new Mongo.Collection("test");

test.sortable('position');

_(10).times(function(n){
  test.insert({name: n});
}
test.findOne({name: 5}).up();
test.findOne({name: 7}).down(2);
_.pluck(test.find().fetch(), "name"); //returns [1,2,3,5,4,6,8,9,7,10]

.trackable()

Adds the trackable pattern.

This pattern is useful to track the evolution of one or more fields. For every update of a document of the collection affecting one of the configured field, a trackRecord is kept. This trackRecord consists of an array of objects, containing the previous value and a trackedAt timestamp stating when this value was changed.

var test = new Mongo.Collection("test");

test.trackable('field1', 'field2');
test.trackable(['field1', 'field2']);

Define your own behaviours

  • Look at the source of the behaviours in the behaviours folder to be able to add your own custom behaviours.
  • Simply register a new behaviour with the CollectionBehaviours.defineBehaviour method.
CollectionBehaviours.defineBehaviour('blamable', function(getTransform, args){
  var self = this;
  self.before.insert(function (userId, doc) {
    doc.createdBy = userId;
  });
  self.before.update(function (userId, doc, fieldNames, modifier, options) {
    if(!modifier.$set)
      modifier.$set = {};
    modifier.$set.lastUpdatedBy = userId;
  });
}

var test = new Mongo.Collection("test");

test.blamable();

Contributors

  • Pieter Soudan (@sewdn)

meteor-collection-behaviours's People

Contributors

bakkie123 avatar chmac avatar davidworkman9 avatar rclai avatar rhythmus avatar svub 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

meteor-collection-behaviours's Issues

Behaviours not attached to Meteor.users

Since an update of Meteor a month or two ago (unfortunately I don't remember what version exactly, but I'd guess it was 0.8.2), the behaviors are missing on the Meteor.users collection.

Currently, I'm using this work around after defining all behaviors and before using any of them on the users collection:

CollectionBehaviours.extendCollectionInstance(Meteor.users);

Behavious do not get attached to Collections automatically

I'm very happy that you continue the collection behavours package. I used it via mrt before and switched to Meteor 1 now.
I noticed one "strange" behaviour, or is it intended?

I wrote a behaviour called "owned" and want to attach it to a collection called "Activities". Here some testing code I wrote (using CoffeeScript):

log CollectionBehaviours
log Activities.owned?
CollectionBehaviours.extendCollectionInstance Activities
log Activities.owned?
Activities.owned()

(FYI, log is just a logger to console; ...? is CoffeeScript's way of checking for a var's existance, i.e. owned? equals typeof owned !== "undefined" && owned !== null in JS)

The output is:

Object {defineBehaviour: function, extendCollectionInstance: function} 
false
true

I.e. I need to call CollectionBehaviours.extendCollectionInstance Activities explicitly so that I can call owned() on the collection. Intentionally? (the mrt version did that automatically somehow)

autoIncrementable does not scale

The current implementation of autoIncrementable does not scale because it relies on an incremented variable per meteor instance. If an application is using multiple meteor instances, the current implementation will produce duplicate autoincrement values!!!

Please use a "Counter Collection" or an "Optimistic Loop" as suggested by the docs:
http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/

Ideally, allow the user to choose between one of the 2 strategies depending on his application needs.

softRemovable and Xolvio/meteor-cucumber

When doing cucumber tests with the package Xolvio/meteor-cucumber the softy removed documents will not be considered as removed. Are there any way to disable softRemovable on a document before I reset my test by doing a Collection.remove({}) so that the document really gets removed?

Timestampable fails when replacing entire documents

Updating an entire document via "collection.update(id, document)" fails:
Exception while simulating the effect of invoking '/activities/update' Error {} Error: When replacing document, field name may not start with '$' as the document gets extended by "$set: { updatedAt: 1384867681991 }".
Timestampable will need to handle this case separately... I'll submit a pull request soon.

Compatibility with collection2 / simple schema

I'm using collection-behaviours along with collection2 and simple schema. I tried adding schema restraints for _id and my own custom userId value (added by a custom collection behaviour). However, the validation fails on these rows. I guess that the validation runs before collection-behaviours modifies the documents.

Is there a way to have the two play nicely? Ideally I'd like collection-behaviours to add my fields and then have collection2 / simple schema validate that everything is in order before the record gets saved.

PS> Thanks for an awesome piece of software, the soft delete function is particularly sweet. ๐Ÿ‘

Upsert support

It seems that the hooks are not called when upsert is used.

I had the bug that the publication doesn't publish any data because softRemovable() was used and the documents were inserted via upsert. This way no documents are published because the softRemovable()-Functionality prevents publishing of documents which doesn't use the softRemovable()-Functionality.

Incorrect git path in Atmosphere

mrt install collection-behaviors

Results in a request for the username and password for github. and an error:

There was a problem cloning repo: https://github.com/sewdn/meteor-collection-behaviours.git

Apparently, this can be caused by an incorrect git path. I manually changed my smart.json to:

"collection-behaviours": {"git":"https://github.com/Sewdn/meteor-collection-behaviours.git"}

And was able to install it properly. Note the capital "S" in "Sewdn."

Timestampable createdAt/By not set when disconnected

Hi, thanks for your package, very useful!

When I'm inserting a document client-side while the connection is down (with Meteor.connection.disconnect()), createdAt and createdBy fields are not set. Looks like they're only set on the server, when the app reconnects. I don't understand why though, because I looked into the code and didn't find anything that would cause this behaviour. I tried to create another .before.insert() and it gets called without problem. What am I missing here?

Thanks!

Error trying to use the package

I'm getting the following error when i try to do

Posts = new Mongo.Collection("posts");
Posts.timestampable();
W20150121-10:04:05.296(11)? (STDERR)
W20150121-10:04:05.297(11)? (STDERR) /Users/rcardoso/.meteor/packages/meteor-tool/.1.0.38.z83ibe++os.osx.x86_64+web.browser+web.cordova/meteor-tool-os.osx.x86_64/dev_bundle/server-lib/node_modules/fibers/future.js:173
W20150121-10:04:05.297(11)? (STDERR)                        throw(ex);
W20150121-10:04:05.297(11)? (STDERR)                              ^
W20150121-10:04:05.298(11)? (STDERR) TypeError: Object [object Object] has no method 'timestampable'
W20150121-10:04:05.298(11)? (STDERR)     at app/lib/collections.js:8:7
W20150121-10:04:05.298(11)? (STDERR)     at app/lib/collections.js:20:3
W20150121-10:04:05.298(11)? (STDERR)     at /Users/rcardoso/Sites/mine/inutil/.meteor/local/build/programs/server/boot.js:175:10
W20150121-10:04:05.298(11)? (STDERR)     at Array.forEach (native)
W20150121-10:04:05.298(11)? (STDERR)     at Function._.each._.forEach (/Users/rcardoso/.meteor/packages/meteor-tool/.1.0.38.z83ibe++os.osx.x86_64+web.browser+web.cordova/meteor-tool-os.osx.x86_64/dev_bundle/server-lib/node_modules/underscore/underscore.js:79:11)
W20150121-10:04:05.298(11)? (STDERR)     at /Users/rcardoso/Sites/mine/inutil/.meteor/local/build/programs/server/boot.js:86:5

What am I doing wrong?

Needs to be migrated to use Mongo.Collection

I think this happened in a very recent update, but I just started building a new app with Meteor 0.9.3 - a console message suggested I use "Mongo.Collection" instead of "Meteor.Collection", but doing so is incompatible with the collection behaviours. I bet they are going for Mongo instead of Meteor for v1.0?

Also, this is one of my favorite packages :)

softRemovable not in place when creating new user

Applying behaviours to the Meteor.users collection is working fine like this:

CollectionBehaviours.extendCollectionInstance(Meteor.users);
Meteor.users.softRemovable();

When I delete a user, the document remains in the database, but is not returned from Meteor.users.find() โ€“ great! The problem arises when the user tries to create a new account with the same e-mail. Meteor says that a user already exists with that e-mail.

Anything I/we can do about this? Thanks.

Version on Atmosphere not working

I've been banging my head into a wall the last couple of days. It turned out that the version of collection-behaviors that got installed with meteor add was 0.1.5, which has a constraint for collection-hooks 0.7.3 โ€“ which doesn't work.

I have three questions:

  1. Wouldn't it be better to not use a hard constraint?
  2. How come Atmosphere doesn't have the newest version? Does it mean that I can never trust Atmosphere again?
  3. Can you solve this or help me solve it?

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.