【问题标题】:Does mongoose createIndex: false mean indexes will be created in the background or not at all?mongoose createIndex: false 是否意味着索引将在后台创建或根本不创建?
【发布时间】:2020-12-16 12:11:26
【问题描述】:

猫鼬docs

当您的应用程序启动时,Mongoose 会自动调用 为架构中每个已定义的索引创建索引。猫鼬会打电话 为每个索引按顺序创建索引,并在 所有 createIndex 调用成功或存在时的模型 一个错误。虽然很适合开发,但建议使用此行为 在生产中被禁用,因为索引创建可能会导致显着 性能影响。通过设置 autoIndex 禁用该行为 您的架构选项为 false,或在连接上全局设置为 将选项 autoIndex 设置为 false。

文档似乎没有解决我们设置 autoIndex: false 时发生的情况。是在后台创建索引还是我必须编写另一个程序或脚本来确保索引在生产中正确完成?

这是否同样适用于所有这些场景?

  • default index 喜欢 _id
  • createdAt 上的索引,例如 someCollection.index({ createdAt: 1 })
  • 内联创建的索引,如new Schema({ someData: { type: String, default: '', index: true})

This thread 暗示我们可以使用 db.ensureIndex({ name: 1 }, { background: true }); 但是当我在 mongoose 文档中寻找类似的语法时,我只发现了以下内容

const userSchema = new Schema({
  email: { type: String, required: true, unique: true },
  registeredAt: { type: Date, index: true }
});

// [ [ { email: 1 }, { unique: true, background: true } ],
//   [ { registeredAt: 1 }, { background: true } ] ]
userSchema.indexes();

注释掉的sectionbackground: true,但它不符合email: { type: String, required: true, unique: true, background: true }, 等架构定义。我不明白他们想在那里表达什么。

This thread...an index build can happen in the "background"... 但我没有在猫鼬文档中看到这一点。也许我错过了它,或者当我的应用程序使用mongoose 处理所有mongodb 操作时,问题可能是不理解何时引用mongoose documentation 而不是mongodb documentation

【问题讨论】:

  • 试试看会发生什么?

标签: mongodb mongoose


【解决方案1】:

看这里https://github.com/Automattic/mongoose/issues/5342 看来选项 { background: true } 是 Mongoose 创建索引时的默认值,您可以覆盖它。

那么关于你的问题:

这是否同样适用于所有这些场景?

  • 默认索引如_id
  • 主索引从集合开始就存在
  • createdAt 上的索引,例如 someCollection.index({ createdAt: 1 })
  • 是的,此索引不会在 autoIndex 关闭的情况下创建
  • 内联创建的索引如 new Schema({ someData: { type: String, default: '', index: true})。
  • 是的,此索引不会在 autoIndex 关闭的情况下创建

【讨论】:

    猜你喜欢
    • 2023-03-26
    • 2012-09-09
    • 2014-08-15
    • 2018-07-25
    • 2015-01-09
    • 2011-09-07
    • 2018-06-14
    • 2010-11-28
    • 2015-06-21
    相关资源
    最近更新 更多