wintzer
wintzer

Reputation: 911

Mongoose Not Creating Indexes

Trying to create MongoDB indexes. Using the Mongoose ODM and in my schema definition below I have the username field set to a unique index. The collection and document all get created properly, it's just the indexes that aren't working. All the documentation says that the ensureIndex command should be run at startup to create any indexes, but none are being made. I'm using MongoLab for hosting if that matters. I have also repeatedly dropped the collection. What is wrong.

var schemaUser = new mongoose.Schema({
    username: {type: String, index: { unique: true }, required: true},
    hash: String,
    created: {type: Date, default: Date.now}
}, { collection:'Users' });

var User = mongoose.model('Users', schemaUser);
var newUser = new Users({username:'wintzer'})
newUser.save(function(err) {
    if (err) console.log(err);
});

Upvotes: 37

Views: 27686

Answers (11)

Yuniac
Yuniac

Reputation: 571

In my case, I had logs model that is meant for Winston logger to automatically store logs in the db and I wasn't using/invoking it manually at all in my application.

The index would never get created no matter what I did.

Later I found out that if a model isn't used at all, it won't be picked up and its indexes won't be built.

So I did this to get around it during my server start:

await LogModel.init();

Upvotes: 0

CACHAC
CACHAC

Reputation: 87

If you have configured your connection string readPreference different from "primary", e.g.:

readPreference=secondaryPreferred or readPreference=secondary

Result:

MongoDB prohibits index creation on connections that read from non-primary replicas.

If this is the case, you should change it to primary, e.g.:

const strconn = `${MONGODB_CONNECTION_STRING}/${DB_NAME}?readPreference=primary`

Upvotes: 0

asafel
asafel

Reputation: 811

Connections that set "readPreference" to "secondary" or "secondaryPreferred" may not opt-in to the following connection options: autoCreate, autoIndex.

Check your readPreference option in the mongoose connection

Upvotes: 4

Henrique Van Klaveren
Henrique Van Klaveren

Reputation: 1760

As you can see in mongoose documentations https://mongoosejs.com/docs/guide.html#indexes, we need define schema.index to create our indexes. Take a look in code below to test:

  • Note, after update your schema restart the server to check.
const schemaUser = new mongoose.Schema(
  {
    username: {
      type: String,
      required: true,
      index: true,
      unique: true,
      dropDups: true,
    },
    hash: String,
    created: {
      type: Date,
      default: Date.now,
    },
  },
  {
    autoCreate: true, // auto create collection
    autoIndex: true, // auto create indexes
  }
)
// define indexes to be create
schemaUser.index({ username: 1 })

const User = mongoose.model('Users', schemaUser)
const newUser = new Users({ username: 'wintzer' })
newUser.save(function (err) {
  if (err) console.log(err)
})

Upvotes: 2

valango
valango

Reputation: 21

I had this problem when writing a data import command-line utility. After execution end, some indexes were created, some were not.

The solution was to call await model.ensureIndexes() before terminating the script. It worked regardless to autoIndex option value.

Upvotes: 1

DannyMoshe
DannyMoshe

Reputation: 6255

In my case I had to explicitly specify autoIndex: true:

const User = new mongoose.Schema({
    name: String,
    email: String,
    password: String
 },
 {autoIndex: true}
)

Upvotes: 6

ArkadiBernov
ArkadiBernov

Reputation: 578

Сheck that the mongoose connect options do not specify :

autoIndex: false

Upvotes: 0

joeytwiddle
joeytwiddle

Reputation: 31257

Mongoose declares "if the index already exists on the db, it will not be replaced" (credit).

For example if you had previous defined the index {unique: true} but you want to change it to {unique: true, sparse: true} then unfortunately Mongoose simply won't do it, because an index already exists for that field in the DB.

In such situations, you can drop your existing index and then mongoose will create a new index from fresh:

$ mongo
> use MyDB
> db.myCollection.dropIndexes();
> exit
$ restart node app

Beware that this is a heavy operation so be cautious on production systems!


In a different situation, my indexes were not being created, so I used the error reporting technique recommended by JohnnyHK. When I did that I got the following response:

E11000 duplicate key error collection

This was because my new index was adding the constraint unique: true but there were existing documents in the collection which were not unique, so Mongo could not create the index.

In this situation, I either need to fix or remove the documents with duplicate fields, before trying again to create the index.

Upvotes: 5

Atiq Ur Rehman
Atiq Ur Rehman

Reputation: 240

It might be solve your problem

var schema = mongoose.Schema({
speed: Number,
watchDate: Number,
meterReading: Number,
status: Number,
openTrack: Boolean,
 });
schema.index({ openTrack: 1 });

Upvotes: 2

Newclique
Newclique

Reputation: 494

When I hooked the index event on the model that wasn't working, I started getting an error on the console that indicated "The field 'retryWrites' is not valid for an index specification." The only place in my app that referenced 'retryWrites' was at the end of my connection string. I removed this, restarted the app, and the index rebuild was successful. I put retryWrites back in place, restarted the app, and the errors were gone. My Users collection (which had been giving me problems) was empty so when I used Postman to make a new record, I saw (with Mongo Compass Community) the new record created and the indexes now appear. I don't know what retryWrites does - and today was the first day I used it - but it seemed to be at the root of my issues.

Oh, and why did I use it? It was tacked onto a connection string I pulled from Mongo's Atlas Cloud site. It looked important. Hmm.

Upvotes: 2

JohnnyHK
JohnnyHK

Reputation: 311835

Hook the 'index' event on the model to see if any errors are occurring when asynchronously creating the index:

User.on('index', function(err) {
    if (err) {
        console.error('User index error: %s', err);
    } else {
        console.info('User indexing complete');
    }
});

Also, enable Mongoose's debug logging by calling:

mongoose.set('debug', true);

The debug logging will show you the ensureIndex call it's making for you to create the index.

Upvotes: 36

Related Questions