【发布时间】:2018-10-13 06:51:46
【问题描述】:
我正在尝试创建一个博客。我有一个用户架构、一个博客架构和一个评论架构。
当我注册一个用户并创建一个博客时,它可以工作(并且可以很好地保存到数据库中)。当我创建另一个用户并且该用户尝试写博客时,我收到一条大错误消息:
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();
}
});
【问题讨论】:
-
将“唯一”放在属性上意味着您需要在其中始终拥有一个值。该错误是因为您在集合中已经有一些没有“用户名”的内容。就像你试图再做一次一样。如果
"username"实际上不是“必需的”,那么您应该删除索引。默认情况下,MongoDB 会将1附加到索引中的字段名称作为索引名称(除非您以其他方式命名)。1表示“升序”顺序。 -
谢谢,但我不明白我需要更改什么。我知道你在告诉我答案……
-
进入shell,选择你的数据库并输入
db.blogs.dropIndexes()。在较早的时候,您的“博客”架构中有“用户名”并创建了索引。当您从架构中删除内容时,Mongoose 不会从数据库中删除索引。删除索引并让猫鼬在重新启动时创建正确的索引(如果有的话)。答案中会提到,所以你应该阅读它们。你不是第一个犯同样错误的人。 -
哇。那行得通。谢谢。所以删除数据库(就像我在更改模型架构时一直在做的那样)不会重置索引?
-
@NeilLunn 又发生了...这次删除索引,删除数据库并不能解决问题。