0

i'm a student of Nodejs. learning for few months. this is one of my practice project. but i'm stuck on an ERROR, that show me - "MongoError: E11000 duplicate key error collection cms_demo1.posts index: username_1 dup key: { : null }". i don't know what to do. pls help.

this is the schema i'm using.

var postSchema = new mongoose.Schema ({
  title: String,
  content: String,
  image: String,
  createdOn: {type: Date, default: Date.now},
});
postSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("post", postSchema);

and this is the post method.

app.post("/posts", function(req, res){        
    var title = req.body.title;
    var content = req.body.content;
    var image = req.body.image;

    var newPost = {title: title, content: content, image: image};
    post.create(newPost, function(err, npost){
        if(err){              
          console.log(err);
        } else {              
          res.redirect("/posts");
        }
    });
});
Sushil
  • 2,324
  • 1
  • 27
  • 26
  • It means that when you were "playing with" different layouts for your schema, you created such a field called `"username"` and defined it as `"unique"`. This created a "unique index". Even though you deleted the data and changed the schema, the index is still there. This is how MongoDB works. So remove the index with `db.posts.dropIndexes()` from the shell. – Neil Lunn Aug 02 '17 at 11:23
  • i droped it, it still shows the same. what can i do now. – Sushil Aug 02 '17 at 11:29
  • You either dropped from the wrong collection or managed to have two models pointing at the one collection. I think it's more likely that you forgot to switch the database namespace when connecting through the mongo shell though. You should have issued `use cms_demo1` first. – Neil Lunn Aug 02 '17 at 11:33
  • after droping, it works only once. after that is shows the same. – Sushil Aug 02 '17 at 11:45
  • It means that you have other code that is creating an index. Somewhere in your code ( either in this program or another one ) you have something pointing to the same collection name with a different schema defined. Mongoose looks at the schema and creates indexes on application start. Turn on debugging with `mongoose.set('debug', true)` so you can track down where this is actually being called. – Neil Lunn Aug 02 '17 at 11:47
  • Mongoose: users.ensureIndex({ username: 1 }, { unique: true, background: true }) Mongoose: posts.ensureIndex({ username: 1 }, { unique: true, background: true }) – Sushil Aug 02 '17 at 12:08
  • it show me the above logs, in the console. – Sushil Aug 02 '17 at 12:09

0 Answers0