Skip to content

Commit 49994b6

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

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
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._rawFind(query, { skip, limit, sort })
19+
.catch(error => {
20+
// Check for "no geoindex" error
21+
if (error.code != 17007 ||
22+
!error.message.match(/unable to find index for .geoNear/)) {
23+
throw error;
24+
}
25+
// Figure out what key needs an index
26+
let key = error.message.match(/field=([A-Za-z_0-9]+) /)[1];
27+
if (!key) {
28+
throw error;
29+
}
30+
31+
var index = {};
32+
index[key] = '2d';
33+
//TODO: condiser moving index creation logic into Schema.js
34+
return this._mongoCollection.createIndex(index)
35+
// Retry, but just once.
36+
.then(() => this._rawFind(query, { skip, limit, sort }));
37+
});
38+
}
39+
40+
_rawFind(query, { skip, limit, sort } = {}) {
41+
return this._mongoCollection
42+
.find(query, { skip, limit, sort })
43+
.toArray();
44+
}
45+
46+
count(query, { skip, limit, sort } = {}) {
47+
return this._mongoCollection.count(query, { skip, limit, sort });
48+
}
49+
}

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)