Home > OS >  Defining mongoose models with bi-directional refs using Model.collection.name
Defining mongoose models with bi-directional refs using Model.collection.name

Time:10-25

Let's say I have 2 schemas

A: {
  someStuff: String,
  children: [{ type: ObjectId, ref: 'B' }]
},
B: {
  someOtherStuff: String,
  parent: { type: ObjectId, ref: 'A' }
}

I would prefer to write the refs as:

A: {
  children: [{ type: ObjectId, ref: modelB.collection.name }]
  ...
},
B: {
  parent: { type: ObjectId, ref: modelA.collection.name }
  ...
}

However, that will give me a circular dependency error.

Is there any way around that, or do I have to stick with the hard-coded collection names?

CodePudding user response:

I beleive there is a way around it directly - but there is a possible work around, if you are very opposed to hard-coded collection names.

You could store the name in a separate file, and have the model, and the reference both consume it.

E.g.

model-names.js
{
  ModelA: 'ModelA',
  ModelB: 'ModelB',
}

Then in model-a.js you could have it "compile" the model with mongoose.model(Names.ModelA) and reference Names.ModelB

I'm not sure I would encourage this for most projects, as it adds some complexity, but I could imagine some use cases with more dynamic model names where it would be nice to just change in one spot.

  • Related