node.js - 嵌套文档中字段上的 Mongoose 索引

标签 node.js mongodb mongoose

我有一个小架构

var PostSchema = new mongoose.Schema({
  title: String,
  link: String,
  author: {type:String,required:true},
  upvotes: {type: Number, default: 0},
  nesteddoc : {
      field1: String
  }
});

//This is broken - index on field1
PostSchema.index({nesteddoc.field1:1},{unique:true});

是否可以通过在 Mongoose 模式中指定而不运行 MongoDB 查询来确保索引在嵌套字段上有索引?

最佳答案

"nesteddoc.field1" 周围使用引号来评估嵌套字段:

PostSchema.index({ "nesteddoc.field1": 1 }, { unique: true });

此外,mongoose 会在内部调用 ensureIndex,从 mongoose doc :

When your application starts up, Mongoose automatically calls ensureIndex for each defined index in your schema. Mongoose will call ensureIndex for each index sequentially, and emit an 'index' event on the model when all the ensureIndex calls succeeded or when there was an error. While nice for development, it is recommended this behavior be disabled in production since index creation can cause a significant performance impact. Disable the behavior by setting the autoIndex option of your schema to false, or globally on the connection by setting the option config.autoIndex to false.

你也可以在模式中定义索引:

var PostSchema = new mongoose.Schema({
    title: String,
    link: String,
    author: { type: String, required: true },
    upvotes: { type: Number, default: 0 },
    nesteddoc: {
        field1: { type: String, unique: true, index: true },
    }
});

关于node.js - 嵌套文档中字段上的 Mongoose 索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42368354/

相关文章:

javascript - 我怎样才能用 promise 重写这个?

node.js - cc1.exe : sorry, 未实现:64 位模式未在退出状态 2 退出状态 1 中编译

node.js - 使用动态查询在 Node 中使用 Mongoose 更新多条记录

node.js - 居住在 Mongoose 中

node.js - 类型错误 : LocalStrategy requires a verify callback

html - 如何使用node/express从现有的mongodb集合中读取数据并将其显示在浏览器上?

php - 缺少 PHP 包括 (.h)

c# - MongoDB 更新失败且没有错误

javascript - 如何检查/迭代 Node 中的对象?

javascript - 在具有不同端口号的单个服务器上运行多个 sails 项目不起作用