Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Duplicate key error index on embedded document in mongoose

Duplicate key error index on embedded document in mongoose

Problem

I am trying to run this simple embedded document using mongoose:

var mongoose = require('mongoose');
var PageSchema = new mongoose.Schema({
    url:String
});
var AlbumSchema = new mongoose.Schema({
    pages:[ PageSchema ]
});

mongoose.model('Album', AlbumSchema);
var Album = mongoose.model('Album');
var album = new Album({pages:[{url:"1"}]});
album.save(function(err, a) {
    console.log(err);
});

After I run this code the second time I get this Error:

{ 
    [MongoError: E11000 duplicate key error index: doalbums.albums.$pages.id_1  dup key: { : null }]
    name: 'MongoError',
    err: 'E11000 duplicate key error index: doalbums.albums.$pages.id_1  dup key: { : null }',
    code: 11000,
    n: 0,
    connectionId: 161,
    ok: 1 
}

What am I doing wrong?

Problem courtesy of: ekeren

Solution

I am not sure what you are doing wrong here,but what is happening is: An index is created for field 'pages' so it does not allow duplicates.To check this you may give this command in mongo shell doalbums.albums.getIndexes()(I think your DB name is doalbums and collection name is albums ) this will list all indexes in "albums". Then remove index that is not required,using db.albums.dropIndex().This will allow duplication. You can refer http://docs.mongodb.org/manual/administration/indexes/

Solution courtesy of: dany

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Duplicate key error index on embedded document in mongoose

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×