【发布时间】: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。显然我不能使用字段级索引,因为有多个字段需要索引(arrayType1、arrayType2、arrayType3)。
【问题讨论】:
标签: node.js mongodb mongoose unique-index mongodb-indexes