Mongo / Mongoose:Mongoose是否自动在ObjectId类型上创建索引?

dip*_*ent 5 javascript mongoose mongodb node.js mongoose-schema

我可能在mongo索引文档或mongoose文档中错过了这一点。

假设我有这样的猫鼬模式:

const SomeEntity = new Schema({
  foo:  { type: String, required: true },
  bar   { type: Schema.ObjectId, ref: 'Bar' }
});
Run Code Online (Sandbox Code Playgroud)

我应该在字段上创建索引bar还是mongo会自动解决这个问题?

换句话说,mongo是否会自动为ObjectId类型创建索引?

rob*_*lep 7

换句话说,mongo是否会自动为ObjectId类型创建索引?

不,MongoDB唯一创建的自动索引是用于_idfield

但是,如果您需要一个索引,则取决于要针对模型运行的查询的类型bar

由于bar是指集合_id中文档的字段bars,因此这些文档本身将由_id将在该集合上创建的自动索引覆盖。

但是,如果您需要能够在“ SomeEntity”集合中找到引用特定栏的文档:

SomeEntity.find({ bar : someBarId })
Run Code Online (Sandbox Code Playgroud)

...那么您可能要为其创建索引:

bar: { type: Schema.ObjectId, ref: 'Bar', index : true }
Run Code Online (Sandbox Code Playgroud)