0

I'm trying to use mongoose to represent an association between 3 schemas:

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
}

Does mongoose support this king of association without creating a schema4?

Ben Diamant
  • 6,186
  • 4
  • 35
  • 50
  • MongoDB documents are based on [JSON](http://json.org/), which only supports key/values in objects and restricts keys to strings. So, the array could be a collection of objects with the keys being the `ObjectId` in string form -- `field: [Schema.Types.Mixed]`. – Jonathan Lonowski Mar 16 '15 at 18:09
  • You may find [How to organise a many to many relationship in MongoDB](http://stackoverflow.com/questions/4839881/how-to-organise-a-many-to-many-relationship-in-mongodb) and [Many-to-many relationships in CouchDB or MongoDB](http://stackoverflow.com/questions/2336700/mongodb-many-to-many-association) of interest, as well as Mongoose's [guide on population](http://mongoosejs.com/docs/populate.html). – Jonathan Lonowski Mar 16 '15 at 18:16

1 Answers1

1

You can't create ambiguous keys in mongoose because its whole purpose is to handle your document structure for you. What you can do, however, is create an array of objects.

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

For future reference it's far easier to understand your question when you provide real examples rather than false names. Even if you falsify your example (e.g. some relationship between restaurants and customers or something) it's much easier to understand the relationship you're trying to make.

jtmarmon
  • 5,727
  • 7
  • 28
  • 45