【问题标题】:How to fix and prevent duplicate key error in mongodb如何修复和防止 mongodb 中的重复键错误
【发布时间】:2019-07-23 01:50:47
【问题描述】:

我最近一直在做一个爱好项目,但我遇到了一个我似乎无法弄清楚的问题,即使在网上搜索了答案之后也是如此。我在带有 MongoDB 的 c9.io 上使用 Node.js。每当我尝试在数据库中创建一个新条目时,第一个条目可以正常工作,但第二个条目会导致错误。

E11000 重复键错误集合:project.tasks 索引:username_1 重复键: { : 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");
      }
   });
});

如果有人知道我做错了什么或者可以引导我找到解决方案,那真是太棒了,因为我已经坚持了一段时间了。

【问题讨论】:

  • 您在任务中有一个字段username

标签: node.js mongodb c9.io


【解决方案1】:

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

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

这个索引很可能是由我们不再看到的以前的代码创建的(或者可能是由 taskSchema.plugin(passportLocalMongoose); ——这听起来很可疑,就像是那种想要在 username 上建立索引的东西)。

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

有关 mongoose 和 mongo 如何交互的更多详细信息,请参阅E11000 duplicate key error index in mongodb mongoose

【讨论】:

  • 感谢您的帮助!!阅读您所说的,我意识到我不需要该护照本地猫鼬,因为它不是用户,然后我放弃了收藏并再次尝试,它可以工作。感激不尽!
猜你喜欢
  • 2018-10-13
  • 2015-05-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-20
  • 2015-01-10
  • 1970-01-01
  • 1970-01-01
  • 2016-09-28
相关资源
最近更新 更多