首页 > 解决方案 > E11000 Node 和 MongoDB 的重复键错误

问题描述

我正在尝试创建一个博客。我有一个用户架构、一个博客架构和一个评论架构。

当我注册用户并创建博客时,它可以正常工作(并且可以很好地保存到数据库中)。当我创建另一个用户并且该用户尝试写博客时,我收到一条大错误消息:

BulkWriteError: E11000 duplicate key error collection: blog.blogs index: username_1 dup key: { : null }

问题是 - 在我的任何模式中都没有键称为username_1. 这是我的架构:

var UserSchema = new mongoose.Schema({
    firstname: String,
    lastname: String,
    username: {
        type: String,
        unique: true
    },
    email: String,
    createdDate: {
        type: Date,
        default: Date.now()
    },
    blogs: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Blog"
        }
    ]
});

博客架构

var BlogSchema = new mongoose.Schema({
    title: String,
    text: String,
    date: {
        type: Date,
        default: Date.now()
    },
    comments: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Comment'
        }
    ],
    author: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User"
    }
});

如果您想知道,发布路线是这样的:

// create a new blog object
            var newBlog = new Blog(
                {
                    title : req.body.title,
                    text : req.body.text,
                    author: foundUser._id
                }
            );

            // create the new blog
            Blog.create(newBlog, function(err, createdBlog) {
                if(err) {
                    console.log(err);
                } else {
                    // push the new blog into the blogs array
                    foundUser.blogs.push(createdBlog);

                    // save to db
                    foundUser.save();
                }
            });

标签: node.jsmongodbmongoose

解决方案


实际上,我认为您的架构中有一个唯一的键。

用户名:{类型:字符串,唯一:真},

也许您可以尝试使用不同的用户名来完成整个事情?


推荐阅读