最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Duplicate key error index on embedded document in mongoose - Stack Overflow

programmeradmin6浏览0评论

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?

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?

Share Improve this question edited Nov 18, 2012 at 10:02 ekeren asked Nov 18, 2012 at 9:56 ekerenekeren 3,4583 gold badges37 silver badges56 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

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 mand 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/manual/administration/indexes/

发布评论

评论列表(0)

  1. 暂无评论