Saturday 1 April 2017

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

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



via Michael

No comments:

Post a Comment