I'd like to use a unique compound index to enforce uniqueness of certain fields of a document.
There are two ways to create indexes when using mongoose:
- By restarting MongoDB
- By calling
Model.ensureIndexes()
(1.) The mongoose documentation clearly states that
When your application starts up, Mongoose automatically calls createIndex for each defined index in your schema.
[...]
While nice for development, it is recommended this behavior be disabled in production since index creation can cause a significant performance impact.
And, well, it does not seem really 'productive' to restart the database each time a new document gets added to a collection.
Same goes for the second way to create an index:
It is not recommended that you run this in production. Index creation may impact database performance depending on your load. Use with caution.
Source
To extend this issue to a specific example:
For each document, the combination of two specific fields shall be unique (f.ex. "year" and "course"), so I'm using a unique compound index.
Right after a new document was saved, there might be a second request with the same values that should trigger an error because it's a duplicate.
If the index has not yet been created, the document will be saved anyway.
So it's about (as the title tries to emphasize) ensuring uniqueness. Maybe using indexes and rebuilding them every time a new document was saved is not the correct approach; I'm open for alternatives.
So how are we supposed to ensure uniqueness then?