Skip to content

Commit 7ac46fb

Browse files
committed
Add MongoCollection and adaptiveCollection abstraction to MongoAdapter.
1 parent 92e51ab commit 7ac46fb

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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+
}

src/Adapters/Storage/Mongo/MongoStorageAdapter.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11

2+
import MongoCollection from './MongoCollection';
3+
24
let mongodb = require('mongodb');
35
let MongoClient = mongodb.MongoClient;
46

@@ -30,6 +32,12 @@ export class MongoStorageAdapter {
3032
});
3133
}
3234

35+
adaptiveCollection(name: string) {
36+
return this.connect()
37+
.then(() => this.database.collection(name))
38+
.then(rawCollection => new MongoCollection(rawCollection));
39+
}
40+
3341
collectionExists(name: string) {
3442
return this.connect().then(() => {
3543
return this.database.listCollections({ name: name }).toArray();

0 commit comments

Comments
 (0)