How to execute native mongo methods in meteor app environment?

Meteor only supports a few methods for mongo collections, such as find, findOne, insert, update, upsert, remove, allow, deny My question is: how do I execute all the others? I want to use a server-side aggregate, for example:

db.eshops.aggregate([ { $unwind: '$unpairedCategories' }, { $group: { _id: '$_id', 'sum': { $sum: 1 } } }, { $group: { _id: null, total_sum: { '$sum': '$sum' } } } ]); 

Should I include the mongodb driver for nodejs separately from the meteor? Or what is the meteor method to launch all other mango collection methods?

+5
source share
1 answer

One of Meteor ’s seven principles is that the database is everywhere, that is, you should be able to perform all permitted operations on both the client and the server (assuming several differences, for example, allow deny rules for the client). I think that’s why you cannot use all the mongo methods: they are unsafe on minimongo, the client version of your mongo collection.

However, if you are ready to give up reactivity , you can create a channel for processing aggregate commands by adding it to the server startup code ( code taken from here ):

 wrapAsync = (Meteor.wrapAsync)? Meteor.wrapAsync : Meteor._wrapAsync; Mongo.Collection.prototype.aggregate = function(pipelines) { var coll; if (this.rawCollection) { // >= Meteor 1.0.4 coll = this.rawCollection(); } else { // < Meteor 1.0.4 coll = this._getCollection(); } return wrapAsync(coll.aggregate.bind(coll))(pipelines); 

You have two possible alternatives / workaround if you want to maintain reactivity.

  • Create additional fields using collections for the collection . You basically include calculated fields in the collection. This is a scalable solution, and it does not require adding extra load to the server.
  • You use the cursor.Observe() function, and you make a combination of smart filtering and JS custom methods (like sum) to achieve similar results with what you need from the aggregate method. Note that you maintain reactivity, but each server (if you plan to scale several) needs Observe() collections. Check out this example: fooobar.com/questions/1226006 / ...
+2
source

All Articles