2

In my NodeJS project, I have created a mongoose schema which I changed midway through the project. More specifically, I added the unique parameter to a field.

However, this change does not seem to reflect as I am still able to create multiple documents with the same value for the parameter which I set as unique

How to fix this issue

Cyborg7459
  • 157
  • 3
  • 10
  • There might be errors while creating the index. Possible because of existing documents don't meet the index constraints. You can check [this question](https://stackoverflow.com/questions/12452865/mongoose-not-creating-indexes/51833357) on how to check for index creation errors. – thammada.ts Jun 24 '21 at 02:11

2 Answers2

0

Mongoose enforces the unique constraint by creating an index in MongoDB with the unique option.

If you already have duplicates in the collection, that index creation will fail.

Note that you may have to call syncIndexes to update the database with the new index.

Joe
  • 25,000
  • 3
  • 22
  • 44
0

Try restarting your node server. Sometimes, changes to the Mongoose model might not take effect until you restart your Node.js application. This is especially true if you're using a development environment

  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 15 '23 at 07:58