How to get userId in the Mongo.Cursor#observeChanges


#1

I wrote Mongo.Cursor#observeChanges at the server side, and I want to get the current userId in the changed(id, fields) function by using this.userId , but I always get undefined… please help me~~

Collection.find().observeChanges({
added: function (id, fields) {

},
changed : function(id, fields) {
console.log(this.userId); //undefined
}
});


#2

You get undefined because of your confusion as to what actually calls your function.

When you use Meteor.methods() you have access to this.userid because that function will (usually) be called by a user, i.e. directly in response to a user action.

observeChanges() on the other hand does not know who or what instigated the change. It could be a user, indeed. It could also be the server thread itself changing something (like a function called by a timer incrementing some kind of counter every minute). It could even be an outside source due to someone changing the data on the MongoDB instance directly without even touching the Meteor app.

This means, basically, that in order to get the userid with observeChanges() you have to provide the userid in the document you just changed, like this:

Meteor.methods({
    updateCollection: function(random_doc_id, data_field1, data_field2) {
        Collection.update({_id: random_doc_id}, {$set: { userid: this.userid, data_field1: data_field1, data_field2: data_field2 } } );
    }
});

And then do this on the client:

Meteor.call("updateCollection", random_doc_id, data_field1, data_field2);

and finally rework your observer like this:

Collection.find().observeChanges({
    added: function (id, fields) {
    .....
    },
    changed : function(id, fields) {
        console.log(fields.userid);
    }
});

Disclaimer: Didn’t actually try to run this code.