javascript - 我可以在模式路径级别和模式级别建立 Mongoose 索引吗?

标签 javascript node.js mongoose

根据 Mongoose 文档,关于 https://mongoosejs.com/docs/guide.html#indexes :

“使用 mongoose,我们在架构中的路径级别或架构级别定义这些索引。”

澄清一下:这意味着我不能有两个不同的索引,一个在架构路径级别定义,另一个在架构级别定义?例如:

var animalSchema = new Schema({
    name: String,
    age: String,
    tags: { type: [String], index: true } // field level
  });

  animalSchema.index({ name: 1, type: -1 }); // schema level

最佳答案

字段级别的只是 .index 函数的糖语法。

因此,如果您已经使用 .index 函数在字段上定义了索引,则它不会再执行任何操作。

在您的示例中,将创建 tags 上的索引以及 name + type 上的索引。

这个:

var animalSchema = new Schema({
    name: String,
    age: String,
    tags: { type: [String], index: true } // field level
  });

相当于这个:

var animalSchema = new Schema({
    name: String,
    age: String,
    tags: { type: [String] }
  });

animalSchema.index({ tags: 1 }); // schema level

关于javascript - 我可以在模式路径级别和模式级别建立 Mongoose 索引吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56140593/

相关文章:

javascript - 调用包含 Promise 的 Async 函数返回未定义

node.js - 错误 : Node Sass does not yet support your current environment: Linux 64-bit with Unsupported runtime (64)

node.js - 无法测试 mongo 聚合 MongoError : Unrecognized pipeline stage name: '$set'

node.js - 操作 `posts.find()` 缓冲在 10000ms 后超时

javascript - jQuery(事件): watch element style

javascript - 如何 promise 一个不包含回调参数的函数?

mysql - 根据 mysql Node 中的第一个结果对表执行查询

循环内的 JavaScript 闭包 – 简单的实际示例

javascript - module.exports = Promise.all 在测试中不起作用

node.js - 将 'GridFSBucketWriteStream' 转换为类型 'WritableStream' 不可能吗?