1

Using Mongoose is it possible to have a field that references another object, when the model/type of that document is unknown?

For example, I have the models: Photos, Comments, Submissions, Posts, etc., and I would like to have a Like model that refers back to them:

var Like = new Mongoose.Schema({
  // What would the value of `ref` be, should it just be left out?
  target: { type: Schema.Types.ObjectId, ref: '*' }
});

From what I understand, ref needs to be a Model. I could leave it out all together, but would I still get the benefit of the Mongoose's populate method that way?

jfelsinger
  • 444
  • 3
  • 12

1 Answers1

1

There are two approaches you can take.

1. Pass in the value of ref when you call populate

Based on the section Populating across Databases. When you call populate, you can specify the model you want to use.

Like.find().populate({
  path: 'target',
  model: 'Photo'   
})

This requires that you know the model you want before you populate.

2. Store the value of ref together with the target

Based on the section Dynamic References.

You need to first adjust the target to something similar to the following:

var Like = new Mongoose.Schema({
  target: {
    kind: String,
    item: {
      type: Schema.Types.ObjectId,
      refPath: 'target.kind'
    }
  }
});

target.kind is the value of "ref" that will be used for populate, and target.item is the ObjectId. We use refPath instead of ref for dynamic references.

Then, when you call populate, you will instead do something like:

Like.find().populate('target.item')

Note that we populate 'target.item' as opposed to just 'target'.

Zsw
  • 3,920
  • 4
  • 29
  • 43