我有一个小架构
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 });
此外,猫鼬会调用ensureIndex
内部,从猫鼬博士 http://mongoosejs.com/docs/guide.html#indexes :
当您的应用程序启动时,Mongoose 会自动调用
确保架构中每个定义的索引的索引。猫鼬会打电话
依次确保每个索引的索引,并发出 'index' 事件
当所有 EnsureIndex 调用成功或有时的模型
一个错误。虽然有利于开发,但建议这样做
在生产中禁用,因为索引创建可能会导致严重的
性能影响。通过设置 autoIndex 禁用该行为
将模式选项设置为 false,或者在连接上全局设置
将选项 config.autoIndex 设置为 false。
您还可以在 schema 中定义索引:
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 },
}
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)