猫鼬架构索引会以奇怪的方式自动创建

时间:2019-09-13 00:45:40

标签: mongodb mongoose indexing

我对mongodb(猫鼬)非常陌生。

我有这三种不同的猫鼬模式,但是由于某种原因,每个模式的索引都以令人惊讶的方式创建。

// user.js file
var UserSchema = new mongoose.Schema({
    username : 
    {
        type : String,
        required : true,
        unique : true
    },

    password : String,
    name : String,
    email : String,
    birthday : Date,
    privilege : Number
});

// in preacher.js
var PreacherSchema = new mongoose.Schema({
    name : 
    {
        type : String,
        require : true,
        unique : true
    },

    desc : String,

    image :
    {
        data : Buffer,
        contentType : String
    }
});

// in event.js file
var EventSchema = new mongoose.Schema({
    name : String,
    theme : String,
    startDate : Date,
    endDate : Date,
    preachers : 
    [
        {
            type : mongoose.Schema.Types.ObjectId,
            ref : "Preacher"
        }
    ],

    schedule : 
    {
        type : mongoose.Schema.Types.ObjectId,
        ref : "Schedule"
    },

    registerList : 
    [
        {
            type : mongoose.Schema.Types.ObjectId,
            ref : "User"
        }
    ]
});

但是,令人惊讶的是,为传教士模式创建的索引具有我不理解的用户名

> db.preachers.getIndexes()
[
    {
        "v" : 2,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_", // I think this one makes sense
        "ns" : "group.preachers"
    },
    {
        "v" : 2,
        "unique" : true,
        "key" : {
            "name" : 1
        },
        "name" : "name_1", // this one too because I set name as unique
        "ns" : "group.preachers",
        "background" : true
    },
    {
        "v" : 2,
        "unique" : true,
        "key" : {
            "username" : 1
        },
        "name" : "username_1", // where is this username coming from? Users? But why?
        "ns" : "group.preachers",
        "background" : true
    }
]

// this is index from users, why is the index copied to preachers?
> db.users.getIndexes()
[
    {
        "v" : 2,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "group.users"
    },
    {
        "v" : 2,
        "unique" : true,
        "key" : {
            "username" : 1
        },
        "name" : "username_1",
        "ns" : "group.users",
        "background" : true
    }
]

在这里创建索引的机制是什么?

由于'username_1'索引,我无法更新第二个文档。

0 个答案:

没有答案