mongodb-js / mongoose-autopopulate

Always populate() certain fields in your mongoose schemas
Apache License 2.0
221 stars 36 forks source link

Does this support populating for multiple fields? #30

Closed appjitsu closed 7 years ago

appjitsu commented 7 years ago

Not only on _id but also some other field?

const ActionSchema = new Schema({
  _id: { type: String, index: true, unique: true },
  label: { type: String },
  type: { type: String },
  order: { type: Number },
  mount: { type: String },
  mountType: { type: String },
  owner: { type: String },
  actions: [{ type: String, ref: 'action', autopopulate: { options: { sort: { order: 1 } } } }], // automatic recursion
  parts: [{ type: String, ref: 'part', autopopulate: true }], // automatic recursion
  parent: { type: String },
  parentType: { type: String },
  parents: { type: Object },
  expanded: { type: Boolean, default: true },
  date: { type: Date, default: Date.now },
  updated: { type: Date, default: Date.now },
});
ActionSchema.plugin(autopopulate); // automatic recursion

So given the above schema, I want to populate on both the _id and the mount. Mount is a foreign key.

So something like this is my use case:

actions: [{ 
    type: String,
    refs: [
      { ref: '_id' refPath: 'actions._id' }, 
      { ref: 'mount' refPath: 'lists._id' }
    ], 
     autopopulate: { options: { sort: { order: 1 } } } 
}],

So I need to pull docs for '_id' from the actions collection and docs for 'mount' from the lists collection.

appjitsu commented 7 years ago

Or maybe dynamic references? http://mongoosejs.com/docs/populate.html#dynamic-ref

vkarpov15 commented 7 years ago

Yeah this plugin should handle dynamic refs transparently, just attach autopopulate: true to mount. This plugin is a very thin wrapper around populate(), all it does is add pre('find') and pre('findOne') hooks that attach the correct populate() calls.