question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Model.syncIndexes() fails with `MongoError: a collection 'dbname.tablename' already exists`

See original GitHub issue

Do you want to request a feature or report a bug? bug

What is the current behavior? run Model.syncIndexes(); for existing model.

If the current behavior is a bug, please provide the steps to reproduce.

https://gist.github.com/rideddy84/a189d839cbef093f719a0e850f2c5ff7.js

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "lib": ["esnext"],
    "module": "commonjs",
    "moduleResolution": "node",
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "outDir": "lib",
    "sourceMap": true,
    "target": "esnext"
  },
  "exclude": ["node_modules"]
}

What is the expected behavior? Indexes are created if they weren’t before.

What are the versions of Node.js, Mongoose and MongoDB you are using? Note that “latest” is not a version. “mongoose”: “5.13.2” Node.js v14.17.0

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:14

github_iconTop GitHub Comments

1reaction
Spowncommented, Jul 14, 2021

What do you mean by sync indexes for existing collections? Do you want to create an index on every collection?

I think he, just like me, wants to force reindex on every app init. Because out-of-the-box, if the raw DB tables have indexes defined, mongoose ignores index settings from mongoose.model(), so you either need to drop indexes before registering a model (this is what I was doing a couple years ago) or run .syncIndexes(). Regardless whether they were changed or not this insures that raw DB and model settings match indexes-wise.

1reaction
IslandRhythmscommented, Jul 7, 2021
const mongoose = require('mongoose');
const {Schema} = mongoose;


const schema = new Schema({ name: { type: String, unique: true } });
const Customer = mongoose.model('Customer', schema);

async function test() {
    await mongoose.connect('mongodb://localhost:27017/test', {
        useNewUrlParser: true,
        useUnifiedTopology: true
      });
    await mongoose.connection.dropDatabase();
    await Customer.collection.createIndex({ age: 1 }); // Index is not in schema

    Customer.collection.getIndexes().then(indexes => {
        console.log(indexes);
    })
    // Will drop the 'age' index and create an index on `name`
    await Customer.syncIndexes();

    Customer.collection.getIndexes().then(indexes => {
        console.log(indexes);
    })
}

test();

The above code runs fine. Copy it and change it to demonstrate your issue. @rideddy84

Read more comments on GitHub >

github_iconTop Results From Across the Web

Initialization error: MongoError: a collection already exists #175
I am using the following constructor new winston.transports.MongoDB({ name: "http", db: process.env.MONGODB_URL, options: { poolSize: 2, ...
Read more >
mongoose index already exists with different options
Right now mongodb allows only one text index per collection. so if you have defined a text index on desc column and try...
Read more >
Connect a Node.js Mongoose application to Azure Cosmos DB
Learn how to use the Mongoose Framework to store and manage data in Azure Cosmos DB.
Read more >
What's New in Mongoose 5.2.0: syncIndexes()
The Model.syncIndexes() function ensures that the indexes defined in your model's schema line up with the indexes in your MongoDB collection ...
Read more >
Meteor with MongoDB Atlas - Index Creation fails
defaultRemoteCollectionDriver().mongo client.db(databaseName).collection(collectionName).createIndex(...) Same Error. Anyone any idea?
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found