buunguyen / mongoose-deep-populate

Mongoose plugin to enable deep population of nested models ⛺
MIT License
469 stars 44 forks source link

deepPopulate function not available #51

Closed kristianmandrup closed 7 years ago

kristianmandrup commented 7 years ago

Trying to follow your example, deepPopulate is not an available function.

  ---
    name: AssertionError
    message: Rejected promise returned by test
    values:
      'Rejection reason:': '[TypeError: Env.findById(...).deepPopulate is not a function]'
    at: 'model._callee$ (packages/red-storage/mongodb/schemas/Project.js:35:10)'

Trying to use it here

      return await Env.findById(id)
        .deepPopulate('branch.commits')
        .where('type ').in(types)
    })

Works without deepPopulate, but then doesn't populate with nested branch/commits (obviously!)

      return await Env.findById(id)
        .where('type ').in(types)
    })

This is my setup

Tried to register locally on Project schema

Project.plugin(deepPopulate)

Trying to register it globally via mongoose.plugin. Is this possible?

var models = require('mongoose-models')
let mongoose = require('mongoose')
mongoose.Promise = global.Promise;

// Register plugins
const deepPopulate = require('mongoose-deep-populate')(mongoose)
const findOrCreate = require('mongoose-findorcreate')

mongoose.plugin(deepPopulate)
mongoose.plugin(findOrCreate)

let methods = {
  envType: async function (types, cb) {
    if (typeof types === 'string') {
      types = [types]
    }
    let envIds = this.environments
    let Env = this.model('Env')
    let envs = envIds.map(async(id) => {
      return await Env.findById(id)
        .deepPopulate('branch.commits')
        .where('type ').in(types)
    })
    return Promise.all(envs)
  }
}

let schema = {
  name,
  description,
  type: String,
  owner: ref('User'),
  environments: refList('Env')
}

models.create('Project', {
  schema,
  methods,
  query: {
    byName: function (name) {
      return this.find({
        name: name
      });
    }
  }
});
buunguyen commented 7 years ago

This plugin adds the method to Query object. Check to make sure mongoose-models returns Query somehow.

kristianmandrup commented 7 years ago

Aha! then I might need to hack mongoose-models some extra ;)

But it does create a normal schema

see here

And I have since hacked it to do props.schema.plugin(yourPluginHere) when it find a plugins entry (Object or Array)

mongoose-models plugins registration

Thanks anyways