Michael
Michael

Reputation: 55

MongoError: E11000 duplicate key error

i'm making a simple blog app using nodejs + express, i can add first post without a problem but when i try to add second post i got his error { MongoError: E11000 duplicate key error collection: restful_blog_app_v2.blogs index: username_1 dup key: { : null }

this is my schema

var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");

var BlogSchema = new mongoose.Schema({
    title: String,
    image: String,
    body: String,
    created: {
        type: Date,
        default: Date.now
    },
    author: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        },
        username: String
    }
});

BlogSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("Blog", BlogSchema);

this is the user schema

var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");

var UserSchema = new mongoose.Schema({
    username: String,
    password: String,
});

UserSchema.plugin(passportLocalMongoose);

module.exports = mongoose.model("User", UserSchema);

this is the create new post route

app.post("/blogs", isLoggedIn, function (req, res) {
    req.body.blog.body = req.sanitize(req.body.blog.body);
    var title = req.body.blog.title;
    var image = req.body.blog.image
    var body = req.body.blog.body;
    var created  = req.body.blog.created;
    var author = {
        id: req.user._id,
        username: req.user.username
    }
    var newPost = {
        title: title,
        image: image,
        body: body,
        created: created,
        author: author
    }
    Blog.create(newPost, function (err, newBlog) {
        if (err) {
            console.log(err);
            res.render("new");
        } else {
            console.log(newBlog);
            res.redirect("/blogs");
        }
    });

});

I've tried to dropped the entire database using db.dropDatabase() from the mongo console but the problem still persist, not sure what to do now

Upvotes: 1

Views: 3410

Answers (2)

Rakesh Vishwakarma
Rakesh Vishwakarma

Reputation: 33

Can you try deleting your Schema and again send the value? I was getting the same issues. I solved with the above idea.

Upvotes: 1

robertklep
robertklep

Reputation: 203231

This is caused by passport-local-mongoose, which, according to its fine manual, makes username a unique field by default.

You have added this plugin to BlogSchema, which seems like you initially had the user data in that schema but moved it to a separate schema (UserSchema) and forgot to remove it from the former.

Start by not using it for BlogSchema, and you also need to drop the unique index on username on the blogs collection.

Upvotes: 2

Related Questions