【问题标题】:Unique and Sparse Schema-level Index MongoDB and Mongoose唯一和稀疏模式级索引 MongoDB 和 Mongoose
【发布时间】:2014-11-11 23:11:55
【问题描述】:

我正在尝试使用 Mongoose 在 MongoDB 中唯一且稀疏的模式的两个字段上创建索引,如下所示:

var ArraySchema = new Schema ({
    user_id: {type: mongoose.Schema.Types.ObjectId, ref:'User'},
    event_id: {type: mongoose.Schema.Types.ObjectId, ref:'Event'}
}, {_id:false});

ListSchema.index({user_id:1, event_id:1}, {sparse:true, unique:true});

然后在用户模式中的数组中使用:

var User = new Schema({
    arrayType1 : {
        type: [ArraySchema]
    },
    arrayType2 : {
        type: [ArraySchema]
    },
    arrayType3 : {
        type: [ArraySchema]
    }
    //More specifications for user schema...
});

但是,当尝试在没有 array 字段的情况下保存多个用户时,重复字段会引发错误。 Mocha 中的错误类似于:array.event_id_1 dup key {null, null}。会抛出此错误的代码段示例如下:

var user1, user2;

user1 = new User({
    username : 'username1',
    password : 'password'
});

user2 = new User({
    username : 'username2',
    password : 'password'
});

user1.save(function() {
    user2.save();
});

这是我使 ArraySchema 的字段唯一且稀疏的原因:如果指定了 array 字段,我不希望数组包含重复的对象;但是,array 字段不是必需的,因此会有很多用户在此字段中拥有null。显然我不能使用字段级索引,因为有多个字段需要索引(arrayType1arrayType2arrayType3)。

【问题讨论】:

    标签: node.js mongodb mongoose unique-index mongodb-indexes


    【解决方案1】:

    似乎不支持做这种事情,至少目前是这样。另一种方法是在这些字段上创建一个复合索引,然后在向字段添加新元素时使用user.arrayType1.addToSet()。这是一个如何工作的示例:

    ArraySchema:

    var ArraySchema = new Schema ({
         user_id: {type: mongoose.Schema.Types.ObjectId, ref:'User'},
         event_id: {type: mongoose.Schema.Types.ObjectId, ref:'Event'}
    }, {_id:false});
    
    ListSchema.index({user_id:1, event_id:1});
    

    用户架构:

    var User = new Schema({
        arrayType1 : {
            type: [ArraySchema]
        },
         arrayType2 : {
             type: [ArraySchema]
        },
        arrayType3 : {
            type: [ArraySchema]
        }
        //More specifications for user schema...
    });
    

    然后我可以像往常一样声明新用户(就像我在问题中所做的那样);但是,例如,当我想向arrayType1 添加新元素时,我将使用以下代码行在新元素尚不存在时添加:

    user.arrayType1.addToSet({user_id : user2._id, event_id : event._id});
    user.save(function(err, result) {
        //Callback logic.
    };
    

    其中user2event 在前面的代码中定义并保存到数据库中。或者,我可以使用 Mongoose 的更新功能:

    User.update({_id : user._id}, {
            $addToSet : {
                arrayType1 : {
                    user_id : user2._id,
                    event_id : event._id
                }
            }
        }, function(err) {
            //Callback logic.
        }
    );
    

    【讨论】:

    • 这也是我的回答:)
    猜你喜欢
    • 2013-06-12
    • 1970-01-01
    • 1970-01-01
    • 2018-06-12
    • 1970-01-01
    • 2015-02-15
    • 1970-01-01
    • 1970-01-01
    • 2014-12-29
    相关资源
    最近更新 更多