node.js - 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();
}
});
解决方案
实际上,我认为您的架构中有一个唯一的键。
用户名:{类型:字符串,唯一:真},
也许您可以尝试使用不同的用户名来完成整个事情?
推荐阅读
- php - Wordpress 标题(使用多个标题)在自定义页面上显示两次
- javascript - ReactJS:如何在服务器中发送多个文件(Laravel)
- android - Kotlin EditText 键监听器仅适用于模拟器
- android - JSON 响应在适配器类上不可读,但在使用改造 http 库的 logcat 上可见
- javascript - 带有 SPA 的 JWT 没有服务器
- c++ - 从服务器到客户端的实时流式传输相机数据
- .net - 将.net 4.5 类库项目的引用添加到.net core 2.1 项目中
- angular - 将代码从 Angular/RXJS 4 重写为 6
- javascript - 如何使引导选项卡仅在单击时加载内容,而不是在页面加载时
- c++ - 模板化接口 - 创建一个通用模板类以返回任何容器