I am trying to create a blog. I have a user schema, a blog schema, and a comment schema.
When I register a user and create a blog, it works (and saves fine to the database). When I create another user and that user tries to write a blog, I get returned a large error message:
BulkWriteError: E11000 duplicate key error collection: blog.blogs index: username_1 dup key: { : null }
The problem is - there is no key in any of my schema's called username_1
. here are my schema's:
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"
}
]
});
Blog schema
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"
}
});
The post route is this in case you want to know:
// 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();
}
});