Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

List of all models #1362

Closed
buschtoens opened this Issue · 8 comments

2 participants

Jan Buschtöns Aaron Heckmann
Jan Buschtöns

Working with mongoose.models is meh. What about mongoose.model() returning an array of all model names like:

var modelNames = mongoose.model() // ["Cars", "Drivers", "Pedestrians"]
  , models = modelNames.map(function(modelName) {
      return mongoose.model(modelName);
    });
Aaron Heckmann
Owner

That would break every app using mongoose. I find it odd that the application itself wouldn't know which models it created.

Jan Buschtöns

Uhm, would it? mongoose.model() used to throw Error: Schema hasn't been registered for model "undefined"
at you. Apps that would rely on this behaviour are IMHO pretty weird.

In my app I use some homebrew Model loader, which regards dependecies. For that it checks which models have yet been loaded (currently mongoose.models.hasOwnProperty(model)). I know that I could build my own array with all loaded Model names, but why not let Mongoose do the work?

Aaron Heckmann
Owner

Oh you're right, I misunderstood.

Models are cached in different ways, for example, if calling mongoose.model its cached at the mongoose level else if calling connection.model its cached at the connection level. Also, you can call x.model() and specify a different collection name as the original which returns the "same" model but subclassed to use the different collection.. so its not a "clean" thing. More of an implementation detail I'd rather not expose.

Jan Buschtöns

Okay, so you would rather prefer a homebrew trycatch?

function hasModel(namespace, name) {
  try {
    namespace.model(name);
  } catch(e) {
    return false;
  }
  return true;
}

console.log(hasModel(mongoose, "Model"));
console.log(hasModel(connection, "Model"));
Aaron Heckmann aheckmann referenced this issue from a commit
Aaron Heckmann aheckmann added; {mongoose,db}.modelNames()
returns array of model names added.

closes #1362
8a38663
Aaron Heckmann
Owner

You convinced me.

Jan Buschtöns

Kudos!

Jan Buschtöns buschtoens closed this
Jan Buschtöns

lib/index.js:328 will opts have a future use ({ includeConnections: true })?

Aaron Heckmann
Owner
Aaron Heckmann aheckmann referenced this issue from a commit
Aaron Heckmann aheckmann added; {mongoose,db}.modelNames()
returns array of model names added.

closes #1362
a785380
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.