I’m wondering if there are any suggestions for managing a custom index on MongoDB with Strapi?
Essentially I want to do some slightly more advanced querying via Mongoose which require certain indexes to be created beforehand. I’m happy to go do this on the database directly, but I’ve noticed that if I do this next time Strapi loads it disappears. I’m currently not 100% sure if this is Mongoose or Strapi removing it. Firstly - any ideas why this might be happening, though I’m about to dig through more docs.
If I can’t find a way to suppress this, what would be the best way to run some code on initialisation that has access to the Strapi models? I appreciate this is by far the worst way, as now I’ve got to incur index creation times too.
I’ve added also some combined indexes manually, and they do not disappear after restart. Can you make some tests with a fresh project? @DMehaffy Can strapi delete indexes on mongo during bootstrap? As I never noticed that happening.
Unfortunately your suggestion on adding an index in a model doesn’t work for me. MongoDB offers a lot of functionality - but often this requires a custom index. So in this case I need a 2dsphere index otherwise I simply can’t query the data via Mongoose because it’s not valid to make a geographic query without first having the index.
Here’s the output of Mongoose during bootstrap. You can clearly see on that last line my index being dropped. At the moment I’ve no data, so generation will be super quick, but later on it could cost a not insignificant amount of time to regenerate, so ideally I wan’t Strapi to just leave it alone.
@sunnyson has the correct method here, do note that currently the index creation only applies to MongoDB at the moment. We need to add some handling for SQL databases that support indexes like this.
Ah, that explains why the indexes are vanishing. I’ve been trying to develop my service at the same time so I’ve created them and then it’s restarting whenever I save a change to the code.
At least in production I can optimise with a compound index later.