Mongoose + Expressjs - E11000 重复键错误索引?

Posted

技术标签:

【中文标题】Mongoose + Expressjs - E11000 重复键错误索引?【英文标题】:Mongoose + Expressjs - E11000 duplicate key error index? 【发布时间】:2016-10-31 01:39:27 【问题描述】:

我不明白为什么在添加第一个条目后出现以下错误:

E11000 duplicate key error index: mydb.datasets.$id_1  dup key:  : null 

我的第一个条目中没有任何空值:


    "index" : "9IPZMW7IL",
    "name" : "Tweets",
    "owner_name" : "xxx",
    "read_key" : "fb6f9125f4ca15c33fea89416c3351d1",
    "write_key" : "d8a6c7e5fc73b5a91aa7a533565ed1f1",
    "data" : 
        "var1" : 
            "name" : "particles"
        
    ,
    "_id" : ObjectId("57729dc20cb70952424cdbb4"),
    "created_at" : ISODate("2016-06-28T15:54:42.576Z"),
    "entries_number" : 0,
    "public" : true,
    "__v" : 0

下面是我的代码:

// CRUD API:
// POST/ Create new dataset request
router.post("/", helper.authenticate, function(req, res) 
    // Used to set the dataset owner
    var sessionUser = req.session.user.name;
    // Get values from the post request
    var name = req.body.name;
    var isPublic = req.body.public != undefined ? true:false;
    // Delete the values from the request body so that we only keep information about the variables
    delete req.body.name;
    delete req.body.public;

    // This is so that we can loop through the object in reverse order
    // We do that so that the fields are saved in the right order on the db
    // (this way it will appear in the right order on the 'edit' view)
    var propertiesList = [];
    for (var property in req.body) 
        if (req.body.hasOwnProperty(property)) 
            propertiesList.push(property);
        
    
    propertiesList.reverse();

    var variablesFields = ;
    for (var i in propertiesList) 
        console.log(propertiesList[i])
        variablesFields[propertiesList[i]] = name:req.body[propertiesList[i]],
                                    values: Array;
    

    // Create dataset
    Dataset.create(
        index: helper.uniqueIndex(),
        name: name,
        owner_name: sessionUser,
        read_key: hat(),
        write_key: hat(),
        public: isPublic,
        data: variablesFields
    , function(err, dataset) 
        if (err) 
            console.log("Error creating the dataset: " + err);
            req.session.error = "A problem occured when creating the dataset. Please try again.";
         else 
            console.log("New dataset created with id: " + dataset._id);
            req.session.success = "Dataset " + name + " created successfully.";
        
        res.redirect("/index");
    );
);

错误:

创建数据集时出错: WriteError("code":11000,"index":0,"errmsg":"E11000 重复键 错误索引:mydb.datasets.$id_1 复制键::null ","op":"index":"2IPZMWHGI","name":"PM 2","owner_name":"xxx","re​​ad_key":"fc31c152aa86070252c70c0304e4ca5c","write_key":"238110753c8762ce4a547fa02100a299","data":"var1":"name":"particles","_id" :"57729dcf0cb70952424cdbb5","created_at":"2016-06-28T15:54:55.459Z","entries_number":0,"public":true,"__v":0)

型号:

var datasetSchema = new mongoose.Schema(
    index: type: String, required: true, index: unique: true,
    name: type: String, required: true,
    owner_name: type: String, required: true,
    read_key: type: String,
    write_key: type: String,
    public: type: Boolean, default: false,
    data: type: Object,
    entries_number: type: Number, default: 0,
    created_at: type: Date, default: Date.now,
    last_entry_at: type: Date
);

知道为什么以及如何解决这个问题吗?

【问题讨论】:

您可能曾经在您的架构中有一个属性id,该属性具有unique : true。现在您将其重命名(为index?),旧的唯一索引仍然存在。见this question。 删除整个数据库并从一个新的数据库开始后它工作正常。 mongo 很奇怪! 您是否先尝试删除有问题的索引? @robertklep 我做到了,但没有运气,所以我不得不放弃数据库并重新开始。现在我遇到了一个更奇怪的 mongo 问题 - ***.com/questions/38090771/… 【参考方案1】:

我通过删除我最初声明为的“id”键解决了这个问题

id:  type: String, unique: true, required: true,

我删除了这一行并删除了初始集合,从而解决了问题。

【讨论】:

以上是关于Mongoose + Expressjs - E11000 重复键错误索引?的主要内容,如果未能解决你的问题,请参考以下文章

使用 Typescript mongoose 填充的 expressjs

使用 DBRef 示例嵌入 ExpressJS 和 Mongoose Schema

使用 DBRef 示例嵌入 ExpressJS 和 Mongoose Schema

Expressjs Mongoose 发现嵌套的嵌入文档未定义

如何在保存在 Mongoose (ExpressJS) 之前在模型中格式化数据

如何在保存在 Mongoose (ExpressJS) 之前在模型中格式化数据