I have a model
var ReferenceSchema = mongoose.Schema({
ownerId:{
type:Number,
required:true,
index: true
},
boardId:{
type:Number,
index:true
},
boardCommentId:{
type:Number,
index: true
},
postId:{
type:Number,
index:true
},
postCommentId:{
type:Number,
index: true
}
});
that stores different previously founded references. It could be references of different types and should be combination of different values:
ownerId - always
boardId + boardCommentId OR postId + postCommentId
And I have this combined indexes:
ReferenceSchema.index({ ownerId: 1, postId: 1 }, { unique: true,sparse: true });
ReferenceSchema.index({ postId: 1, postCommentId: 1 }, { unique: true,sparse: true });
ReferenceSchema.index({ boardId: 1, boardCommentId: 1 }, { unique: true,sparse: true });
Problem is when I'm trying to add new document, I have an error E11000 duplicate key error index: db.references.$ownerId_1_postId_1 dup key: { : 33390409, : null }
even with sparse:true
. Am I using sparse incorrectly or I need another approach with compound indexes and sparse?