Passing Object Method as Parameter in JavaScript

208 views Asked by At

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!

1

There are 1 answers

0
Bergi On

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);