4

I recently started to use Mongoose (v.3.2.1) and I am having problems with the indexes.

I define a couple of indexes on my schema ( Schema.path('attr').index(true) ) and they are not being created in the DB. (I run db.collection.getIndexKeys() in the shell and I only see the _id index).

Note that sometimes some/all of the indexes are created.

I turned on debugging and I see the ensureIndex() running:

mongoose.set('debug', true);

Mongoose: myColl.ensureIndex({ type: 1 }) { safe: true, background: true }  
Mongoose: myColl.ensureIndex({ created: 1 }) { safe: true, background: true }  
Mongoose: myColl.ensureIndex({ updated: 1 }) { safe: true, background: true }  

I also listened for errors:

mongoose.connection.on('error', function(err) {
    console.error('MongoDB error: %s', err);
});

myCollModel.on('index',function(err) {
    console.error('MongoDB error: %s', err);
});

I can see my inserts and queries in the console but no error.

Any help will be greatly appreciated!

Thanks,

Nitzan Bar

My Schema is defined like this:

myColl = new Schema();

myColl.add({
     text : { type: String, required : true }
   , shortText: { type: String }
   , type : { type: String , index: true}
   , correctAnswerId : { type: ObjectId, ref: QuestionAnswer}
   , answers: { type: [ QuestionAnswer ] }
});

In this case 'type' index is not created. Note that sometimes after running the ensureIndexes() for a couple of times they are created.

Thanks!

Nitzo
  • 79
  • 6

2 Answers2

0

When defining a field that's an ObjectId reference to a document in another collection, the ref attribute's value is the string name of the model, not the model itself. So it should look like this instead:

correctAnswerId : { type: ObjectId, ref: 'QuestionAnswer' }

I have a feeling that the timing of that failure is impacting whether the type index is created or not.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • 1
    Thanks I tried that but still having the same problem. I even removed the field completely and still the index is not created. – Nitzo Oct 11 '12 at 22:17
0

Indeed, I had the same problem.

And then I copy the ensureindex debug info into mongo terminal to try it out, the command was sent (just as shown from mongoose console), but the creation is failed due to the problem of mongo:

{
    "err" : "ns name too long, max size is 128",
    "code" : 10080,
    "n" : 0,
    "connectionId" : 78,
    "ok" : 1
}

then I give the option {name: 'super_index'}, then it is done.

Hope it is helpful for you!

Ye Huang
  • 639
  • 2
  • 10
  • 21