Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Autoindex is recreating existing indexes #14597

Closed
2 tasks done
GustavoOS opened this issue May 16, 2024 · 3 comments
Closed
2 tasks done

Autoindex is recreating existing indexes #14597

GustavoOS opened this issue May 16, 2024 · 3 comments

Comments

@GustavoOS
Copy link

Prerequisites

  • I have written a descriptive issue title
  • I have searched existing issues to ensure the bug has not already been reported

Mongoose version

8.3.4

Node.js version

20.13.1

MongoDB server version

3.6

Typescript version (if applicable)

No response

Description

When connecting with autoIndex option set true (which is the default), mongoose will create the indexes every time the application runs.

Steps to Reproduce

  1. Create a project with mongoose
  2. Create a model with an index
  3. Connect with autoIndex and 'debug' set
  4. Start the application
  5. The index creation will be logged (correct)
  6. Stop the application
  7. Start the application again
  8. The index creation will be logged again (unexpected)

Expected Behavior

Autoindex only create indexes that weren't previously created

@vkarpov15
Copy link
Collaborator

This is expected and documented behavior. If this behavior is incorrect for your use case, you can disable autoIndex option and use Model.syncIndexes() instead.

syncIndexes() does exactly what you suggest: check MongoDB for which indexes already exist, drop any indexes that are in MongoDB but not in schema, create any indexes that are in schema but not in MongoDB, do nothing with indexes that exist in both schema and MongoDB.

@GustavoOS
Copy link
Author

This is expected and documented behavior. If this behavior is incorrect for your use case, you can disable autoIndex option and use Model.syncIndexes() instead.

syncIndexes() does exactly what you suggest: check MongoDB for which indexes already exist, drop any indexes that are in MongoDB but not in schema, create any indexes that are in schema but not in MongoDB, do nothing with indexes that exist in both schema and MongoDB.

syncIndexes does something different, as this syncs Indexes only by each model, not for all models as autoIndex does

@vkarpov15
Copy link
Collaborator

There's also a Connection.prototype.syncIndexes() which calls syncIndexes() on every model in the collection: https://mongoosejs.com/docs/api/connection.html#Connection.prototype.syncIndexes()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants