|
| 1 | + |
| 2 | +let mongodb = require('mongodb'); |
| 3 | +let Collection = mongodb.Collection; |
| 4 | + |
| 5 | +export default class MongoCollection { |
| 6 | + _mongoCollection:Collection; |
| 7 | + |
| 8 | + constructor(mongoCollection:Collection) { |
| 9 | + this._mongoCollection = mongoCollection; |
| 10 | + } |
| 11 | + |
| 12 | + // Does a find with "smart indexing". |
| 13 | + // Currently this just means, if it needs a geoindex and there is |
| 14 | + // none, then build the geoindex. |
| 15 | + // This could be improved a lot but it's not clear if that's a good |
| 16 | + // idea. Or even if this behavior is a good idea. |
| 17 | + find(query, { skip, limit, sort } = {}) { |
| 18 | + return this._mongoCollection |
| 19 | + .find(query, { skip, limit, sort }) |
| 20 | + .toArray() |
| 21 | + .catch(error => { |
| 22 | + // Check for "no geoindex" error |
| 23 | + if (error.code != 17007 || |
| 24 | + !error.message.match(/unable to find index for .geoNear/)) { |
| 25 | + throw error; |
| 26 | + } |
| 27 | + // Figure out what key needs an index |
| 28 | + let key = error.message.match(/field=([A-Za-z_0-9]+) /)[1]; |
| 29 | + if (!key) { |
| 30 | + throw error; |
| 31 | + } |
| 32 | + |
| 33 | + var index = {}; |
| 34 | + index[key] = '2d'; |
| 35 | + //TODO: condiser moving index creation logic into Schema.js |
| 36 | + return this._mongoCollection.createIndex(index) |
| 37 | + // Retry, but just once. |
| 38 | + .then(() => this.find(query, { skip, limit, sort })); |
| 39 | + }); |
| 40 | + } |
| 41 | + |
| 42 | + count(query, { skip, limit, sort } = {}) { |
| 43 | + return this._mongoCollection.count(query, { skip, limit, sort }); |
| 44 | + } |
| 45 | +} |
0 commit comments