Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

mongodb - Mongoose unique index on subdocument

Let's say I have a simple schema:

var testSchema = new mongoose.Schema({
    map: { type: [ mongoose.Schema.Types.Mixed ], default: [] },
    ...possibly something else
});

Now let's ensure that pairs (_id, map._id) are unique.

testSchema.index({ _id: 1, 'map._id': 1 }, { unique: true });

Quick check using db.test.getIndexes() shows that it was created.

{
    "v" : 1,
    "unique" : true,
    "key" : {
        "_id" : 1,
        "map._id" : 1
    },
    "name" : "_id_1_map._id_1",
    "ns" : "test.test",
    "background" : true,
    "safe" : null
}

The problem is, this index is ignored and I can easily create multiple subdocuments with the same map._id. I can easily execute following query multiple times:

db.maps.update({ _id: ObjectId("some valid id") }, { $push: { map: { '_id': 'asd' } } });

and end up with following:

{
    "_id": ObjectId("some valid id"),
    "map": [
        {
            "_id": "asd" 
        },
        {
            "_id": "asd" 
        },
        {
            "_id": "asd" 
        }
    ]
}

What's going on here? Why can I push conflicting subdocuments?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Long story short: Mongo doesn't support unique indexes for subdocuments, although it allows creating them...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...