猫鼬索引

时间:2013-12-14 17:57:18

标签: javascript node.js mongodb express mongoose

我遇到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_"
  }
]

1 个答案:

答案 0 :(得分:1)

为每个创建的文档自动创建_id字段。您无法更改其名称或将其删除。

employeesSchema将有2个主键:

  • employee._id
  • employee.employeeId

这就是你在猫鼬中看到两个索引的原因


编辑:

创建模型后,我们必须在创建文档之前等待索引事件

User = mongoose.model('users', UserSchema);

User.on('index', function () {
   new User({}).save();
   new User({}).save();
   new User({}).save();
   new User({}).save();
})

如果您不等待索引事件,则可能无法创建索引(并且您不会看到mongoose发出的任何警告)

我已将此报告给mongoose并就此问题获得回复: https://github.com/LearnBoost/mongoose/issues/1745