Mongoose Indexing
Mongoose Indexing
我在Mongoose中的索引有问题。我有一个employeeId字段,它是唯一的。当我创建一个员工文档时,它会创建一个索引"employeeId_1",而且我发现还有一个索引"id"。我想它应该是"_id"。有人能纠正我做错了什么吗?这是代码:
var mongoose = require('mongoose');
var ObjectId = mongoose.SchemaTypes.ObjectId;
var eContactSchema = mongoose.Schema({
contacttype:{type: Number},
name:{type: String, required:true},
phone:{type: String, trim: true},
mail1:{type: String, trim: true},
mail2:{type: String, trim: true},
city:{type: String, trim: true},
state:{type: String, trim: true},
zip:{type: String, trim: true}
})
var eCourseSchema = mongoose.Schema({
course:{type: ObjectId, required:true, unique: true},
title:{type: String},
notes:{type: String, trim:true},
expire:{type: Date},
deleted: {type: Boolean, default: false}
})
var eAppSchema = mongoose.Schema({
appName:{type: String, required: true, trim: true},
view:{type: Boolean, default: false},
create:{type: Boolean,default: false},
edit:{type: Boolean,default: false},
del:{type: Boolean,default: false}
})
var employeesSchema = mongoose.Schema({
firstName:{type: String, trim:true, required:true},
lastName:{type: String, trim:true, required:true},
employeeId: {type: String, trim:true, required:true, unique: true},
active: {type: Boolean, default: true},
admin: {type: Boolean, default: false},
title: {type: String, trim:true},
pin:{type:String, trim: true},
contacts:[eContactSchema],
courses:[eCourseSchema],
apps:[eAppSchema]
})
module.exports = db.model('employees', employeesSchema,'employees');
以下是我创建文档的方法。
exports.addEmployee = function (data, callback) {
employees.create(data, function (err) { callback(err) });
};
以下是getIndex结果。由于某些原因,我无法重新创建该问题,但同时还会有另一个名为employeeId_1的索引。它将在密钥employeeId_1上消除一个重复错误。
[
{
"v": 1,
"key": {
"_id":1
},
"ns": "Management.employees",
"name": "_id_"
}
]
为创建的每个文档自动创建_id字段。您不能更改其名称或将其删除。
employeesSchema将有两个主键:
- 员工_id
- employee.employeeId
这就是为什么你在猫鼬中看到两个索引
编辑:
创建模型后,我们必须等待索引事件,然后才能创建文档
User = mongoose.model('users', UserSchema);
User.on('index', function () {
new User({}).save();
new User({}).save();
new User({}).save();
new User({}).save();
})
如果您不等待索引事件,则可能不会创建索引(并且您不会看到来自猫鼬的任何警告)
我已经向猫鼬报告了这一情况,并得到了关于这个问题的回复:https://github.com/LearnBoost/mongoose/issues/1745
相关文章:
- 使用promise和mongoose对文档进行排序
- 如何缩短MongoDB ObjectId并在Mongoose模式中使用它
- mongoose.connect undefined不是一个函数
- Mongoose-在更新中删除数组元素
- 在mongoose中使用正则表达式在对象数组中进行查询搜索
- Mongoose TypeError:实例化模式类型的对象时,对象不是函数
- 预保存钩子:mongoose中回调的顺序如何
- Mongoose传递类函数
- 将mongoose javascript代码转换为typescript.此引用丢失
- Mongoose查询嵌套文档的时间或多或少为某个日期
- Node.js和Mongoose返回2D查询
- 从Mongoose结果匿名函数返回父函数
- 返回一个关联数组,而不是mongoose中的文档数组
- Mongoose从查询中设置本地变量
- Mongoose查询在两个日期时间之间提取数据
- Mongoose响应解析不正确
- Mongoose:布尔型'或者'使用通配符查询
- 为什么我的Mongoose findAll方法返回500错误.
- 使用mongoose将数据推送到mongoDB模式中的数组中
- Mongoose Indexing