How does Meteor receive updates to the results of a MongoDB query?


I asked a question a few months ago, to which Meteor seems to have the answer.

Which, if any, of the NoSQL databases can provide stream of *changes* to a query result set?

How does Meteor receive updates to the results of a MongoDB query?



9/22/2017 6:01:22 PM

Accepted Answer

From the docs:

  • On the server, a collection with that name is created on a backend Mongo server. When you call methods on that collection on the server, they translate directly into normal Mongo operations.

  • On the client, a Minimongo instance is created. Minimongo is essentially an in-memory, non-persistent implementation of Mongo in pure JavaScript. It serves as a local cache that stores just the subset of the database that this client is working with. Queries on the client (find) are served directly out of this cache, without talking to the server.

When you write to the database on the client (insert, update, remove), the command is executed immediately on the client, and, simultaneously, it's shipped up to the server and executed there too. The livedata package is responsible for this.

That explains client to server

Server to client from what I can gather is the livedata and mongo-livedata packages.

Hope that helps.

4/16/2012 3:21:43 PM

You want query.observe() for this. Say you have a Posts collection with a tags field, and you want to get notified when a post with the important tag is added.

// collection of posts that includes array of tags
var Posts = new Meteor.Collection('posts');

// DB cursor to find all posts with 'important' in the tags array.
var cursor = Posts.find({tags: 'important'});

// watch the cursor for changes
var handle = cursor.observe({
  added: function (post) { ... }, // run when post is added
  changed: function (post) { ... } // run when post is changed
  removed: function (post) { ... } // run when post is removed

You can run this code on the client, if you want to do something in each browser when a post changes. Or you can run this on the server, if you want to say send an email to the team when an important post is added.

Note that added and removed refer to the query, not the document. If you have an existing post document and run

Posts.update(my_post_id, {$addToSet: {tags: 'important'}});

this will trigger the 'added' callback, since the post is getting added to the query result.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow