如何修复和防止MongoDB中的重复键错误

时间:2019-03-01 03:51:50

标签: node.js mongodb c9.io

我最近一直在从事一个业余项目,即使在互联网上寻找答案后,也遇到了一个似乎无法解决的问题。我正在使用MongoDB在c9.io上使用Node.js。每当我尝试在数据库中创建一个新条目时,第一个条目都可以正常工作并且运行顺利,但是第二个条目会导致错误。

E11000重复密钥错误集合:project.tasks索引:username_1 dup密钥: {:null}'

我的架构:

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

var taskSchema = new mongoose.Schema({
    task: String,
    region: String,
    cost: String,
    when: String,
    isAccepted: Boolean,
    author: {
        id:{
            type: mongoose.Schema.Types.ObjectId, 
            ref: "User"
        }
    },
    tasker: {
        id : { 
          type: mongoose.Schema.Types.ObjectId,
          ref: "User"
        }
    }
}); 

taskSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("Task", taskSchema);

我的帖子请求:

app.post("/taskers/index/show", function(req, res){
   var task = req.body.task;
   var newTask = {
      task: task.task, 
      region: task.region, 
      cost: task.cost, 
      when: task.when, 
      isAccepted: false, 
      author: req.user._id, 
      tasker: req.user._id
   };
   console.log("STSOTSOTSOTOOPP");
   Task.create(newTask, function(err, newlyCreated){
      if(err){
         console.log(err);
      } else {
         console.log(newlyCreated);
         res.redirect("/users/index");
      }
   });
});

如果有人知道我在做什么错或者可以导致我解决问题,那将是令人惊讶的,因为我已经坚持了一段时间。

1 个答案:

答案 0 :(得分:0)

  

E11000 duplicate key error collection: project.tasks index: username_1 dup key: { : null }

此错误来自mongo(不是来自mongoose)。从猫鼬模式中删除索引不会对基础集合产生任何影响,因此您现在要从username集合中删除tasks上的唯一索引。

此索引很可能是由我们不再看到的以前的代码创建的(或者可能由taskSchema.plugin(passportLocalMongoose);创建的-听起来像是一种需要在username上建立索引的东西)。 / p>

如果使用外壳连接到mongo,则应该运行db.tasks.getIndexes()来查看唯一的用户名索引,然后使用dropIndexCommand删除有问题的索引。

有关猫鼬和mongo互动方式的更多详细信息,请参见E11000 duplicate key error index in mongodb mongoose