MongoDB嵌入式文档为key-val数组

时间:2015-03-16 18:01:45

标签: node.js mongodb mongoose

我试图使用mongoose来表示3个模式之间的关联:

Schema1: {
    //fields
}

Schema2: {
    //fields    
}

Scehma3: {
   //fields
   - [Scehma1:Scehma2] - collection of key-val elements
     where the key is a ref to schema1 and val is ref to scehma2
}

mongoose是否支持这个关联之王而不创建schema4?

1 个答案:

答案 0 :(得分:1)

您无法在mongoose中创建模糊键,因为它的全部目的是为您处理文档结构。但是,你可以做的是创建一个对象数组。

Schema4: {
  schemaRefs: [{
    refToSchema1: {type: mongoose.Types.ObjectId, ref: 'Schema1'},
    refToSchema2: {type: mongoose.Types.ObjectId, ref: 'Schema2'}
  }]
}

为了将来参考,当您提供真实示例而非虚假名称时,您更容易理解您的问题。即使你伪造你的榜样(例如餐馆和顾客之间的某种关系或某些东西),你也可以更容易理解你想要建立的关系。