子文档上的猫鼬唯一索引 [英] Mongoose unique index on subdocument

查看:28
本文介绍了子文档上的猫鼬唯一索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个简单的架构:

Let's say I have a simple schema:

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

现在让我们确保对 (_id, map._id) 是唯一的.

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

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

使用 db.test.getIndexes() 快速检查显示它已创建.

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
}

问题是,这个索引被忽略了,我可以轻松地创建多个具有相同 map._id 的子文档.我可以轻松地多次执行以下查询:

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' } } });

并最终得到以下结果:

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

这是怎么回事?为什么我可以推送冲突的子文档?

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

推荐答案

长话短说:Mongo 不支持子文档的唯一索引,尽管它允许创建它们...

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

这篇关于子文档上的猫鼬唯一索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆