Joe
Joe

Reputation: 1535

MongoDB array index

I want to create a simple filesystem implementation with mongodb.

Consider the schema,

FSSchema = new mongoose.Schema({
    fname : String,
    path : [String],
    content : Schema.Types.Mixed,
    user : {
       type : Schema.ObjectId,
       ref : 'User'
    }
})    
// Create compount index
FSSchema.index({ path : 1 , fname : 1 } , { unique : true })
mongoose.model('Data', DataSchema)

However my unit tests fail when creating two distinct entries

user1 = new Data({ fname : 'name'}, path: ['fld1','fld2']})
user1 = new Data({ fname : 'name'}, path: ['fld1','fld3']})

which respectively should refer to 'fld1/fld2/name' and 'fld1/fld3/name'. The failure is because apparently only 'name' and 'fld1' get used in the index.

How would I go about creating such a compound index?

Note: I know the obvious solution is to have path as a single string with a file separator such as '/'. Just wondering if using string arrays in indices is possible.

Upvotes: 0

Views: 800

Answers (1)

WiredPrairie
WiredPrairie

Reputation: 59763

You'll need to combine the path into a single value. It's an intentional feature of MongoDb that each element of any array is indexed, so you're seeing the duplicate error when trying to insert the same two values. If having the path as distinct directories is important, you may want to double store the data, once as a full path for uniqueness, and a second as you have it. Don't enforce uniqueness though on the array as you had done.

Upvotes: 2

Related Questions