Can I make all my subscriptions non-reactive in Meteor - meteor

Would it be possible to make all my subscriptions non-reactive?
This means, that once the inicial set has been sent to the client, server stops observing the cursors.
I found the following answer here: Are non-reactive Meteor db subscriptions possible?
This works, but I'd prefer a "global" solution.
Ideally, I'd like to have the option to choose which subscriptions would be reactive and which won't. For example, I'd like to have all logged in "admin" users to have reactive data, however, regular website visitors don't need this.
Thanks! :)

You can by simply adding {reactive: false} on your publication options.
// This code only runs on the server
Meteor.publish("company", function companyPublication(){
if (this.userId) {
return Company.find({userId: this.userId},{limit:1, reactive:
false});
} else {
return this.ready();
}
});

Related

How to Reproduce Meteor.user() Client-Server effect for a different Collection?

Just how Meteor.user() method is available on Client & Server for the "current user" I would love to reproduce this kind of functionality for different custom collections. For example, my app uses a "clouds" collection as a type of room for a group of users to be in. Obviously there are various cloud instances and I don't always want to be passing the cloudId into every single meteor method. Ideally I could have like a Meteor.cloud() function that would give me the current cloud on the client and server.
My thoughts on approaching this:
What I have been doing thus far is piggy-backing off of Meteor.user() by storing a currentCloudId property inside the user profile and setting that on a route beforeAction. However this limits the user to only being in 1 cloud at a time.
Using the Meteor.connection ID somehow to keep a map of connectionIds to cloudIds. This would work great in theory....however it seems that Meteor connection IDs cannot be heavily relied on as they might change during reconnects or other random scenarios. Also you would have to then "manange" that collection of "cloudConnections" and remove old stale ones and such.
Im using Iron Router....and if it were possible to get the current route data on the server that would also solve my problem but I am not sure how to access that on the server?
--- Basically I would love for a simple straight forward way to mimic Meteor.user() behavior for other collections.
Thanks for all your help :)
You can just create a function inside /lib that looks something like this:
getUserClouds = function getUserClouds () {
return Clouds.find({ $elemMatch: { $eq: Meteor.userId() } })
}
This will work both on the client and on the server. But it will always return a Cursor pointing to 0 docs. So you'll need a publication:
Meteor.publish('userClouds', function () {
return Clouds.find({ $elemMatch: { $eq: this.userId } })
})

Meteor publication with calculations

I have 2 collections: Meteor.users and Projecs.
Users collection have field "projects" which contains array of user's project's ids.
"projects" : [
"jut6MHx6a7kSALPEP",
"XuJNvq7KTRheK6dSZ"
]
Also I have a publication for user's projects:
Meteor.publish('projects', function() {
var userProjects = Meteor.users.findOne(this.userId).projects;
return Projects.find({_id: {$in: userProjects}});
});
Everything works fine, but when I add new project (and update users ("projects" field) who are in this project) reactive publication doesn't works. Projects page doesn't contains recently added project. It works only when I refresh page.
Subscription made in router:
waitOn: function() {
return [
Meteor.subscribe('projects')
]
},
What should I do with this publication? Thanks a lot.
This is happening because Meteor.users is not reactive. I don't know what the reason behind but I saw many developers, specially developers who try to get famous by publish really cool articles about their awesome application, exposing the tokens.
So if some idiot publish the Meteor.users to the browser, it's a security flaw. It would be even worst if it was reactive because the token would be updated in realtime. Maybe this a block to newbie who don't really know that they're doing. Just my opinion about this decision.
This collection is design to be used for managing users and after the login, it makes no sense to use to store data, as it is designed.
Yea, this is a known "problem". Publish functions aren't reactive, so Meteor.users.findOne(this.userId).projects will only be evaluated when the client subscribes. You'll find a lot of information about this if you search for "meteor reactive joins", for example https://www.discovermeteor.com/blog/reactive-joins-in-meteor/
In your case, the clients will always have access to their array of project ids, right? Then the simplest solution would probably be to do something like this on the client:
Tracker.autorun(function(){
var user = Meteor.user()
if(user){
Meteor.subscribe(user.projects)
}
})
So, when the client notices that the array of project ids has changed, it renews the subscription (I'm unsure if passing user.projects to the subscribe call is necessary, but I'm a bit afraid that the subscription isn't is renewed if it's called with the same arguments as before).
Using the reactive-publish package (I am one of authors) you can do:
Meteor.publish('projects', function () {
this.autorun(function (computation) {
var userProjects = Meteor.users.findOne(this.userId, {fields: {projects: 1}}).projects;
return Projects.find({_id: {$in: userProjects}});
});
});
Just be careful to limit the first query only to projects so that autorun is not rerun for changes in other fields.

Meteor, get all users on a specific page

We are building a chat application and are currently working on a system to see all the users in a given room.
We have a Mongo Document set up with an array of active_users where we will push and pull user names to in order to keep track of the online users. We have come to the conclusion that realizing a user has connected to a given room is fairly simple. All we need to do is in the router, when a user accesses the page, we push that user's name into the document.
Now the tricky part is realizing when that user has left that given page? Obviously jQuery isn't a reliable option, so how do we know when a user's connection to a specific page is broken?
You could do this:
Meteor.publish("page", function() {
this._session.socket.on("close", function() {
//Change your active users here
});
});
and for your page that you track
Meteor.subscribe('page');
I use this in the analytics package on atmosphere
There's an Atmosphere package called Presence that does exactly what you need.
Some extra details from the README about keeping track of custom states...
State functions
If you want to track more than just users' online state, you can set a custom state function. (The default state function returns just 'online'):
// Setup the state function on the client
Presence.state = function() {
return {
online: true,
currentRoomId: Session.get('currentRoomId')
};
}
Now we can simply query the collection to find all other users that share the same currentRoomId
Presences.find({ state: { online: true, currentRoomId: Session.get('currentRoomId') } })
Of course, presence will call your function reactively, so everyone will know as soon as things change.
Meteor has connection hooks so you can run a function when the user disconnects from the server. Setting the onClose() callback inside a method called by the client will allow you to close the userId in the function.
Code on the server could be like this:
Meteor.methods({
joinRoom: function( roomId ){
var self = this;
Rooms.update( {roomId: roomId}, {$push:{userId: self.userId}});
self.connection.onClose( function(){
Rooms.update( {roomId: roomId}, {$pull:{userId: self.userId}})
});
}
});

How to know when user document loaded in Meteor Accounts

I understand that when writing code that depends on the collection being loaded into the client minimongo, that you should explicitly subscribe to the collection and pass in the appropriate callback for when it is finished loading.
My problem is that I store a lot of important subdocuments that my page needs to access in the users collection. I am using Meteor Accounts, and am trying to figure out a similar way to wait until the entire logged in user document is available. When using this to test:
console.log(Meteor.user());
the logged in case, it seems like it first registers an object with just the _id, and then sends the other fields later (I know I have to explicitly add other fields to publish from the server beyond email, etc.).
Is there a way for me to wait for the logged in user document to load completely before executing my code?
Thanks!
Deps.autorun (previously Meteor.autorun) reruns when something reactive changes, which might fit your use case:
Client js
Deps.autorun(function () {
if(Meteor.user() {
//Collection available
}
});
If you're using a subscription you can also use its callback. Have a read about it on the docs as you might have to customize it a bit, and remove the autopublish package as well as get your other collections set up to subscriptions
Server js:
Meteor.publish("userdata", function () {
//You might want to alter this depending on what you want to send down
return Meteor.users.find({}, {}});
});
Client js
Meteor.subscribe("userdata", function() {
//Collection available
});

Meteor: How can I tell when the database is ready?

I want to perform a Meteor collection query as soon as possible after page-load. The first thing I tried was something like this:
Games = new Meteor.Collection("games");
if (Meteor.isClient) {
Meteor.startup(function() {
console.log(Games.findOne({}));
});
}
This doesn't work, though (it prints "undefined"). The same query works a few seconds later when invoked from the JavaScript console. I assume there's some kind of lag before the database is ready. So how can I tell when this query will succeed?
Meteor version 0.5.7 (7b1bf062b9) under OSX 10.8 and Chrome 25.
You should first publish the data from the server.
if(Meteor.isServer) {
Meteor.publish('default_db_data', function(){
return Games.find({});
});
}
On the client, perform the collection queries only after the data have been loaded from the server. This can be done by using a reactive session inside the subscribe calls.
if (Meteor.isClient) {
Meteor.startup(function() {
Session.set('data_loaded', false);
});
Meteor.subscribe('default_db_data', function(){
//Set the reactive session as true to indicate that the data have been loaded
Session.set('data_loaded', true);
});
}
Now when you perform collection queries, you can check if the data is loaded or not as:
if(Session.get('data_loaded')){
Games.find({});
}
Note: Remove autopublish package, it publishes all your data by default to the client and is poor practice.
To remove it, execute $ meteor remove autopublish on every project from the root project directory.
Use DDP._allSubscriptionsReady() (Meteor 0.7)
As of Meteor 1.0.4, there is a helper that tells you exactly when a particular subscription is ready: Template.instance().subscriptionsReady().
Since this question is a duplicate, please check my answer in the original question, Displaying loader while meteor collection loads.
You can also do template level subscriptions:
Template.name.onCreated(function(){
var self = this;
this.autorun(function(){
const db = this.subscribe('publicationname', [,args]);
if(db.isReady()){
"You'll know it's ready here" .. do what you need.
}
});
})
This makes it easier to know inside the template too. you can just call
{{#if Template.subscriptionsReady}}
{{else}} Loading Screen may be
{{/if}}
You could check when a result is finally returned if you know that your Games collection is never empty:
Meteor.autorun(function() {
if(Games.findOne() && !Session.get("loaded")) {
Session.set("loaded",true);
//Its ready..
console.log(Games.findOne({}));
}
});
You can also use this in your templates:
Client js:
Template.home.isReady = function() { return Session.get("loaded") };
Html
<template name="home">
{{#if isReady}}
Yay! We're loaded!!
{{else}}
Hold an a second
{{/if}}
</template>
Here is another tidbit of information for those who may be using userid or some part of user info stored in Meteor.users database. When the page first loads the Meteor subscribe, going on in the background, may not be complete itself. Therefor when you try to connect to another database to query for that, it will not pull the information. This is because the Meteor.user() is still null itself;
The reason, like said above, is because the actual Meteor users collection has not gotten through pulling the data.
Simple way to deal with this.
Meteor.status().connected
This will return true or false, to let you know when the Meteor.user collection is ready. Then you can go on about your business.
I hope this helps someone, I was about to pull my hair out trying to figure out how to check the status. That was after figuring out the Meteor user collection itself was not loaded yet.

Resources