E11000与Node和MongoDB重复键错误

时间:2018-05-03 04:16:52

标签: node.js mongodb mongoose

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

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

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();
                }
            });

1 个答案:

答案 0 :(得分:0)

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

  

用户名:{      type:String,      独特:真实   },

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

相关问题