簡體   English   中英

貓鼬索引

[英]Mongoose Indexing

我在貓鼬索引中遇到問題。 我有一個唯一的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字段是為創建的每個文檔自動創建的。 不能更改其名稱或將其刪除。

employeeSchema將具有2個主鍵:

  • 員工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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM