【问题标题】:Why is MongoDB creating indexes for fields that don't exist within that schema?为什么 MongoDB 为该模式中不存在的字段创建索引?
【发布时间】:2019-02-16 00:24:29
【问题描述】:

TL;DR:我的 mongo 数据库似乎从我的用户集合中的字段为我的板集合创建索引时遇到问题,这在我尝试创建新板时导致 E11000 错误。

我正在构建一个看板(如 Jira)并拥有看板、任务和用户集合(实体关系图:https://imgur.com/a/Nu6Eg91)。在 .dropIndexes() 之后,所有集合都可以正常工作。但是,当我通过一个板上的 UI 处理任务时,当我尝试创建另一个板时,我收到此 E11000 错误:

{ MongoError: insertDocument :: caused by :: 11000 E11000 duplicate key error index: kanban.boards.$username_1  dup key: { : null }
    at Function.create (/home/ubuntu/workspace/kanban v1.0/node_modules/mongodb-core/lib/error.js:43:12)
    at toError (/home/ubuntu/workspace/kanban v1.0/node_modules/mongodb/lib/utils.js:149:22)
    at coll.s.topology.insert (/home/ubuntu/workspace/kanban v1.0/node_modules/mongodb/lib/operations/collection_ops.js:859:39)
    at /home/ubuntu/workspace/kanban v1.0/node_modules/mongodb-core/lib/connection/pool.js:532:18
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)
  driver: true,
  name: 'MongoError',
  index: 0,
  code: 11000,
  errmsg: 'insertDocument :: caused by :: 11000 E11000 duplicate key error index: kanban.boards.$username_1  dup key: { : null }' }

这似乎是由于板架构中的用户名字段中的空值,但此模型中没有这样的字段,如下所示:

// Board Schema

// Config
var mongoose = require("mongoose"),
    passportLocalMongoose = require("passport-local-mongoose");


// Create Board Schema

var BoardSchema = new mongoose.Schema({
    user: {type: mongoose.Schema.Types.ObjectId, ref: "User", unique: true, sparse: true},
    todo: [{type: mongoose.Schema.Types.ObjectId, ref: "Task"}],
    inProgress: [{type: mongoose.Schema.Types.ObjectId, ref: "Task"}],
    testing: [{type: mongoose.Schema.Types.ObjectId, ref: "Task"}],
    completed: [{type: mongoose.Schema.Types.ObjectId, ref: "Task"}]
});


// Validation
BoardSchema.plugin(passportLocalMongoose);


// Export Model
module.exports = mongoose.model("Board", BoardSchema);

这是数据库中的示例板:

{ "_id" : ObjectId("5c65767c8977670a2366ffe5"), 
"todo" : [ ObjectId("5c657a1e451bc80ac315ef35"), ObjectId("5c657a4a451bc80ac315ef37"), ObjectId("5c657a76451bc80ac315ef39") ], 
"inProgress" : [ ObjectId("5c6579e1451bc80ac315ef31"), ObjectId("5c657a03451bc80ac315ef33"), ObjectId("5c657a3a451bc80ac315ef36"), ObjectId("5c657a8a451bc80ac315ef3a") ], 
"testing" : [ ObjectId("5c657a9a451bc80ac315ef3b") ], 
"completed" : [ ObjectId("5c657a60451bc80ac315ef38"), ObjectId("5c65bb8f6f5b731aec27b4a7"), ObjectId("5c65bba06f5b731aec27b4a8"), ObjectId("5c657a11451bc80ac315ef34") ], 
"user" : ObjectId("5c65767b8977670a2366ffe4"), 
"__v" : 51 }

出于某种原因,我认为数据库已经为 board 模式创建了用户名索引。板子集合的索引如下:

[
        {
                "v" : 1,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "kanban.boards"
        },
        {
                "v" : 1,
                "key" : {
                        "user" : 1
                },
                "name" : "user_1",
                "ns" : "kanban.boards",
                "background" : true
        },
        {
                "v" : 1,
                "unique" : true,
                "key" : {
                        "username" : 1
                },
                "name" : "username_1",
                "ns" : "kanban.boards",
                "background" : true
        }
]

为了完整起见,这里是用户架构:

// User Schema

// Config

var mongoose = require("mongoose"),
    uniqueValidator = require("mongoose-unique-validator"),
    passportLocalMongoose = require("passport-local-mongoose");


// Create User Schema

var UserSchema = new mongoose.Schema({
    username: {type: String, required: true, unique: true},
    password: String
});


// Validation and Hash/Salt PW
UserSchema.plugin(uniqueValidator, {message: "A user is already registered with that {PATH}."});
UserSchema.plugin(passportLocalMongoose);


// Export Model
module.exports = mongoose.model("User", UserSchema);

导致错误的代码在注册路径中,部分如下图:

// create new board for user
        var newBoard = {
            user: user._id,
            todo: [],
            inProgress: [],
            testing: [],
            review: [],
            completed: [],
        };


        Board.create(newBoard, function(err, board) {
            if(err) {
                console.log(err);
                req.flash("error", "Uh oh! Something went wrong.");
                return res.redirect("/");
            }

            // authenticate user
            passport.authenticate("local")(req, res, function() {
                req.flash("success", "Welcome to your Kanban board, " + user.username + ".");
                return res.redirect("/board");
            });

        });

我不明白为什么要创建这个索引(或者确实这是导致 E11000 错误的原因,但我很确定它是)。为代码的垃圾邮件道歉,我对使用 mongo 非常缺乏经验,所以不知道什么是相关的,什么不是。我之前已经构建了具有多个集合的 mongo 数据库,但没有像我在这里那样使用链接集合,所以我无法弄清楚出了什么问题。如果我错过了任何有用或重要的内容,请告诉我。谢谢。

【问题讨论】:

  • 您是否尝试过手动删除索引,并查看它是否会自动重新创建?

标签: node.js mongodb mongoose indexing


【解决方案1】:

我不能 100% 确定这是否是问题所在,但您应该从 BoardSchema.user 参数中删除 unique: truesparse: true。由于您在 UserSchema 中声明了它们,因此您不应该在 BoardSchema 中也需要它们。

编辑:完成第一步后,您可能还必须手动删除索引。

【讨论】:

  • 我在问题首次出现后添加了这些参数以尝试修复它,但我再次删除了它们并删除了数据库。到目前为止,问题已解决,但我会密切关注。谢谢。
  • 停止db和node服务器并在12小时后重新启动后,用户名索引已返回。
【解决方案2】:

问题是我将 passport-local-mongoose 插入到 board 架构中,而这应该只在用户架构上。

【讨论】:

    猜你喜欢
    • 2020-03-22
    • 2019-03-10
    • 1970-01-01
    • 2015-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-25
    • 2022-09-30
    相关资源
    最近更新 更多