首页 文章

MongoDB数组索引

提问于
浏览
0

我想用mongodb创建一个简单的文件系统实现 .

考虑架构,

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)

但是,创建两个不同的条目时,我的单元测试失败

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

分别应该引用'fld1 / fld2 / name'和'fld1 / fld3 / name' . 失败是因为显然只有'name'和'fld1'在索引中使用 .

我将如何创建这样的复合指数?

注意:我知道明显的解决方案是将路径作为带有文件分隔符(如“/”)的单个字符串 . 只是想知道是否可以在索引中使用字符串数组 .

1 回答

  • 2

    您需要将路径合并为单个值 . MongoDb的一个故意特征是任何数组的每个元素都被索引,因此当您尝试插入相同的两个值时,您会看到重复的错误 . 如果将路径作为不同的目录很重要,您可能需要将数据双重存储,一次作为唯一性的完整路径,然后再将其存储为第二次 . 尽管在阵列上执行时不要强制执行唯一性 .

相关问题