Mongo / Mongoose:Mongoose 会自动在 ObjectId 类型上创建索引吗?
Mongo / Mongoose: Does Mongoose automatically create indexes on ObjectId types?
我可能在 mongo 索引文档或 mongoose 文档中遗漏了这一点。
假设我有这样一个 mongoose 架构:
const SomeEntity = new Schema({
foo: { type: String, required: true },
bar { type: Schema.ObjectId, ref: 'Bar' }
});
我应该在字段 bar
上创建索引还是 mongo 会自动解决这个问题?
换句话说,mongo 会自动为 ObjectId 类型创建索引吗?
In other words, does mongo automatically create indexes for ObjectId types ?
不,MongoDB创建的唯一自动索引is for the _id
field。
但是,如果您需要 bar
.
的索引,这取决于您要针对您的模型 运行 的查询类型
由于 bar
引用 bars
集合中文档的 _id
字段,这些文档本身将被创建的自动 _id
索引覆盖在那个系列上。
但是如果您需要能够在 "SomeEntity" 集合中找到引用特定柱的文档:
SomeEntity.find({ bar : someBarId })
...那么你可能想为它创建一个索引:
bar: { type: Schema.ObjectId, ref: 'Bar', index : true }
我可能在 mongo 索引文档或 mongoose 文档中遗漏了这一点。
假设我有这样一个 mongoose 架构:
const SomeEntity = new Schema({
foo: { type: String, required: true },
bar { type: Schema.ObjectId, ref: 'Bar' }
});
我应该在字段 bar
上创建索引还是 mongo 会自动解决这个问题?
换句话说,mongo 会自动为 ObjectId 类型创建索引吗?
In other words, does mongo automatically create indexes for ObjectId types ?
不,MongoDB创建的唯一自动索引is for the _id
field。
但是,如果您需要 bar
.
由于 bar
引用 bars
集合中文档的 _id
字段,这些文档本身将被创建的自动 _id
索引覆盖在那个系列上。
但是如果您需要能够在 "SomeEntity" 集合中找到引用特定柱的文档:
SomeEntity.find({ bar : someBarId })
...那么你可能想为它创建一个索引:
bar: { type: Schema.ObjectId, ref: 'Bar', index : true }