0

我正在爲Mongo集合編寫JavaScript單元測試。我有一個集合的數組,我想爲這些集合產生一個項目數的數組。具體而言,我有興趣使用Array.prototype.map。我希望是這樣的工作:在JavaScript中傳遞對象方法作爲參數

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

但是,相反,我得到一個錯誤,告訴我,Mongo.Collection.find是不確定的。我認爲這可能與Mongo.Collection是一個構造函數而不是實例化對象有關,但我想了解一些更好的事情。有人可以解釋爲什麼我的方法不工作,我需要改變,以便我可以通過find方法map?謝謝!

+0

所以'fooCollection'和如'Mongo.Collection'實例?你在第一次打電話時想要「發現」什麼? –

+2

也許你真的想使用'Mongo.Collection.prototype.find'? – apsillers

+0

啊哈。我也這樣想,並嘗試過,但它仍然給我未定義的錯誤。我再次嘗試,並意識到'Mongo.Collection.prototype.find' _does_工作。問題在於'map'爲每個元素調用'find(arrayItem)'而不是'arrayItem.find()'。我可以通過地圖匿名程序來做我想做的事情。無論如何,這可能會更好,因爲我可以從單個函數返回計數,而不是調用兩次「map」。謝謝您的幫助。 – Reggie

回答

0

findcount是需要在集合實例上作爲方法調用的原型函數(具有適當的this上下文)。 map不這樣做。

最好的解決辦法是使用箭頭功能:

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

但也有an ugly trick,讓你做無:

const counts = collections 
.map(Function.prototype.call, Mongo.Collection.prototype.find) 
.map(Function.prototype.call, Mongo.Collection.Cursor.prototype.count);