If I have some schema defined like this:
schema = new Schema({_some_array_field: [{type: String, index: true}]})
There's no index on _some_array_field if I check with getIndexes() from the shell.
I need to explicitly do schema.index({_some_array_field: 1})
UPDATE: It looks like if I specify the array field like this, the index gets applied:
schema = new Schema({_some_array_field: {type: [String], index: true}})
So it seems to be relating to how the index options are being parsed out.
this is by design as you have discovered.
I don't understand what you mean when you say it's "by design". Is the [{type: String}]
syntax not supposed to be use in favor of {type: [String]}
? If so, then there's a different bug and it's that documentation is out of date, since the documentation still shows the former for array fields and not the latter.
new Schema({_some_array_field: [{type: String, index: true}]})
creates a document array
new Schema({_some_array_field: [String] })
creates an array of strings
Let me know where the docs are incorrect so we can get that fixed.
http://mongoosejs.com/docs/populate.html
There are places where we try do something like [{type: Schema.ObjectId, ref: 'SomeOtherSchema', index: true}]
and that's where we were running into this.
@azylman there isn't any reference to index
on that page.
No, there isn't, but that's where it shows using the syntax [{type: Schema.ObjectId, ref: 'SomeOtherSchema'}]
instead of something like {type: [Schema.ObjectId], ref: 'SomeOtherSchema'}
which you said was wrong. We have a field like that, that we need to have an index on, and when I add index: true
to it it wasn't applying the index because of the initial issue I opened.
Oh sorry I'm wrong:
new Schema({_some_array_field: [{type: String, index: true}]}) creates a document array
That's just an array of strings.
Yeah that ref option is an oddball. Normally path options are all declared outside the arrays. We should look into fixing that. I'll open an issue and refer to this - hopefully someone tackles it soon.
So is there any way to have an array of ObjectIds that ref something and are indexed without doing schema.index({_some_field: 1})
- basically to have it all declared at the path level?
@azylman and @aheckmann any resolution the question above, was just wondering the same thing?
this _seems_ to work:
properties : { type: [{ type: ObjectId, ref: 'Property' }], index: true },
Most helpful comment
this _seems_ to work: