Search code examples
node.jsdatabasemongodbmongooseunique

MongoDB E11000 duplicate key error collection with no unique field in schema


I'm setting up a simple blog form with title, content, and json base64 image data to pass to a local MongoDB server. This is my post route:

router.post('/:userName/posts/new', isAuthenticated, async (req, res) => {
    let parsedImage = req.body.file != null && req.body.file != '' ? JSON.parse(req.body.file).data : ''

    const newPost = new Post({
        title: req.body.title,
        content: req.body.content,
        imageJson: parsedImage
    })

    try {
        await newPost.save()
        res.redirect("/account")
    } catch (e) {
        console.log(e)
        res.redirect("/home")
    }
})

And this is my schema model:

const mongoose = require('mongoose');

const postSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true,
    },
    content: {
        type: String,
        required: true,
    },
    imageJson: {
 

           type: String
        }
});
    
    module.exports = mongoose.model('Post', postSchema)

no unique: true as you can see. The first time I tried running this, it ran perfectly, redirecting directly to the /account page, as intended in the try catch block. But, on a second attempt, using a different image, different content, and different title, it threw this error:

MongoError: E11000 duplicate key error collection: fullstacksus.posts index: userName_1 dup key: { userName: null }

I have no idea what's going on since userName is a database name used in my user account route, but not in my post-making route. Why is it showing up again? Thanks for your answers.


Solution

  • In your MongoDB there is a unique index on {userName: 1}. Since your schema does not have a userName field, it is missing, i.e. null, in every document, so the index rejects it.

    Use the mongo shell to connect and drop the index.