Im setting up my MongoDB models, and I have one models schema (Partition
model) setup in such a way that one of the schema items (fields
) is an array of items that follows another schema (Field
schema)
Here's the Partition model (with the Partition schema and the Field schema):
// Partition model
module.exports = Mongoose => {
const Schema = Mongoose.Schema
// Field Schema
const fieldSchema = new Schema({
name: {
type: Schema.Types.String
}
})
// Partition Schema
const partitionSchema = new Schema({
name: {
type: Schema.Types.String
},
// `fields` is an array of objects that must follow the `fieldSchema`
fields: [ fieldSchema ]
})
return Mongoose.model( 'Partition', partitionSchema )
}
Then I have another model (Asset
model), which has an attributes
array, which holds objects that each have two items, _field
and value
. the _field
needs to be an ID that will reference an item in the Partition models fields._id
values.
Heres the Asset model:
// Asset model
module.exports = Mongoose => {
const Schema = Mongoose.Schema
const assetSchema = new Schema({
attributes: [{
// The attributes._field should reference one of the Partition field values
_field: {
type: Schema.Types.ObjectId,
ref: 'Partition.fields' // <-- THIS LINE
},
value: {
type: Schema.Types.Mixed,
required: true
}
}],
// Reference the partition ID this asset belongs to
_partition: {
type: Schema.Types.ObjectId,
ref: 'Partition'
}
})
return Mongoose.model( 'Asset', assetSchema )
}
Where I'm running into issues, is with the _field
item in the Asset
schema. Im not sure what I should set as the ref
value, since its referencing a sub-schema (meaning the Field
schema within the Partition
schema)
I may have overlooked it in the docs, but I didn't see anything. How can I reference a models sub-schema, so when I populate that item in the query, it populates it with the sub-documents inside the Partition
model documents?
Ive tried to reference the field documents as Partition.fields
, which resulted in the error:
MissingSchemaError: Schema hasn't been registered for model "Partition.fields".
I tried the above ref
value based on what I read from another SO thread, but it doesn't seem to work.