Skip to content

Commit 56a0107

Browse files
Merge pull request #94 from tungv/auto-index-on-create-store
feat: create index for all the models when create mongodb store
2 parents 4922794 + e7eb348 commit 56a0107

File tree

1 file changed

+14
-0
lines changed
  • packages/jerni-store-mongodb/src

1 file changed

+14
-0
lines changed

packages/jerni-store-mongodb/src/store.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,14 @@ export default async function makeMongoDBStore(config: MongoDBStoreConfig): Prom
111111
// use test logger if NODE_ENV is test
112112
const logger = process.env.NODE_ENV === "test" ? testLogger : config.logger || defaultLogger;
113113

114+
// run initial setup for the store. currently there are 2 things:
115+
// 1. ensure snapshot collection for each model exists with the newest version
116+
// 2. ensure theses indexes are created:
117+
// - { __v: 1, __op: 1 } for optimistic concurrency control
118+
// - { __v: -1, __op: -1 } for sorting by version number
119+
// - { __v: 1 }
120+
// => for mongodb compound index rule, only `{ __v: 1, __op: 1 }` is enough
121+
114122
await runDb(async (_, db) => {
115123
const snapshotCollection = db.collection<SnapshotDocument>("jerni__snapshot");
116124

@@ -132,6 +140,12 @@ export default async function makeMongoDBStore(config: MongoDBStoreConfig): Prom
132140
},
133141
);
134142
}
143+
144+
// ensure indexes
145+
for (const model of models) {
146+
const fullCollectionName = getCollectionName(model);
147+
await db.collection(fullCollectionName).createIndex({ __v: 1, __op: 1 }, { name: "jerni__optimistic" });
148+
}
135149
});
136150

137151
async function* listen() {

0 commit comments

Comments
 (0)