0

I'm writing JavaScript unit tests for Mongo collections. I have an array of collections and I would like to produce an array of the item counts for those collections. Specifically, I'm interested in using Array.prototype.map. I would expect something like this to work:

const collections = [fooCollection, barCollection, bazCollection];
const counts = collections.map(Mongo.Collection.find).map(Mongo.Collection.Cursor.count);

But instead, I get an error telling me that Mongo.Collection.find is undefined. I think this might have something to do with Mongo.Collection being a constructor rather than an instantiated object, but I would like to understand what's going on a little better. Can someone explain why my approach doesn't work and what I need to change so that I can pass the find method to map? Thanks!

Reggie
  • 413
  • 2
  • 9
  • 19
  • So `fooCollection` and such are `Mongo.Collection` instances? And what are you trying to `find` in the first call? – T.J. Crowder Dec 27 '16 at 17:14
  • 2
    Perhaps you actually want to use `Mongo.Collection.prototype.find`? – apsillers Dec 27 '16 at 17:18
  • Aha. I thought that too and tried it, but it still gave me the undefined error. I tried it again and realized that `Mongo.Collection.prototype.find` _does_ work. The problem is that `map` calls `find(arrayItem)` for each element rather than `arrayItem.find()`. I can pass map an anonymous procedure to do what I want. This is probably better anyway because then I can return the count from a single function, rather than calling `map` twice. Thanks for the help. – Reggie Dec 27 '16 at 18:30

1 Answers1

0

find and count are prototype functions that need to be invoked as methods (with the proper this context) on the collection instance. map doesn't do that.

The best solution would be to use arrow functions:

const counts = collections.map(collection => collection.find()).map(cursor => cursor.count())

but there is also an ugly trick that lets you do without:

const counts = collections
.map(Function.prototype.call, Mongo.Collection.prototype.find)
.map(Function.prototype.call, Mongo.Collection.Cursor.prototype.count);
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375