BagrijRoman
BagrijRoman

Reputation: 249

Meteor collection observe changes rightly

Good morning. Have a little troubles with meteor collection observing.

I try to catch moments, when my collection is changed (added recor, removed ...)

The problem is, my observer "added" function is called not only when i add document to collection, but it calls when i run meteor project and meteor system add already existing records to database. (it calls for each exisiting document from collection)

Please help me to configure my observer, i need to catch only changes from user, but not from starting system initialization. Maybe it's the way init my observer on the server side after meteor database initialization?

Here is my code:

/app/collections/collections.js

groups = new Mongo.Collection('groups');

groups.allow({
    insert:function(){
        return true;
    },
    update:function(){
        return true;
    },
    remove:function(){
        return true;
    }
});

/server/observers/groups_observer.js

groups.find().observe({
added: function(document){
    console.log('groups observe added value function');
    console.log(document);
},
changed:function(new_document, old_document){
    console.log('groups observe changed value function');
},
removed:function(document){
    console.log('groups observe removed value function');
}
});

Upvotes: 4

Views: 3249

Answers (1)

BagrijRoman
BagrijRoman

Reputation: 249

The way to resolve this problem is:

  • add created_at field to documents

  • add new documents filter to observer by created_at field

When i add doc to collection:

groups.insert({
            created_by:Meteor.userId(),
            created_at: new Date(),
            .......
        });

new, worked version of observer

var now = new Date();
groups.find({created_at : {$gt:now}}).observe({
    added: function(document){
        console.log('groups observe added value function');
        console.log(document);
    },
    changed:function(new_document, old_document){
        console.log('groups observe changed value function');
    },
    removed:function(document){
        console.log('groups observe removed value function');
    }
});

Here was resolved the same problem: cursor.observe({added}) behavior in Meteor

Thanks @Francesco Pezzella for help)

Upvotes: 4

Related Questions