DocumentDB Index Creation Automation
So the problem with DocumentDB is that it will not create the indexes we’ve defined in our NestJS/NodeJS app automatically unlike the MongoDB itself. To see the issue you can start by checking out to this commit sha app and then try start the app and then opening the localhost:9002 in your browser:
docker compose up -d
The username and password for the mongo-express is “root” and “pass”. Then you can open the my-awesome-auto-index-db database and go to posts collection, there you’ll see all the indexes who have been created automatically.
Solution
You need to hook into the onApplicationBootstrap lifecycle event of NestJS and try to call the createIndex API directly. You also need to turn off the auto index creation of mongoose.
Considerations
- You need to use the
Schema.indexAPI instead of defining the indexes in the@Propdecorator, this happens because we are not able give the index a name and it will be an auto generated one by the mongoose.- Make sure that you are following this guideline, otherwise your application won’t be able to run.
- DocumentDB has a max length on index name, so you cannot choose a really long name (ref).
- ≤ 127 characters.
- We need to call
createCollectionAPI before trying to get index and or create them. - DocumentDB has another limitation, that is that we cannot create multiple indexes at the same time, so that is why I am getting all the defined indexes in the code and create them one after another for a given collection.
-
If you need to create an index on a field in a shared nested-document, you need to create it in the collection which is using the shared nested schema, similar to users collection.
And if the field is an array of objects, the syntax does not change at all. You can look at accounts collection for reference.
Default Value for a New Field
- I wanted to add
rolefield to the user collection. - But with no database migration.
- And its value should be calculated if not provided when we are creating a new document like this:
- If
isVerifiedfield istruethen they’re user. - Else they are guest.
- If
How to Test
docker compose up -d
Then open mongo-express to create a new user without any value or role field, but with a isVerified. Then try to fetch all users: http://localhost:3000/users.