36
var UserSchema = new Schema({...}); // Schema
var User = mongoose.Model('User', UserSchema); // Model
var user = new User({...}); // Document

given just the document (user in this case), is there an easy way to get the model (User in this case) without prior knowledge about what model the document refers to? There's a user.schema, but as far as I can tell, no user.model.

The context is given a document and a path, I want to tell if there are other objects with an equal value for that path in the DB.

Thanks.

Brian
  • 2,499
  • 3
  • 24
  • 26

1 Answers1

72

Assume you have a user variable that is an instance of the User model, but this will work for any mongoose model instance var Model = user.constructor; now you can do Model.find() to run your query and this will work on any collection.

If you need the name of the model, it can be accessed via user.constructor.modelName.

Alexis Tyler
  • 1,394
  • 6
  • 30
  • 48
Peter Lyons
  • 142,938
  • 30
  • 279
  • 274
  • Thanks! Didn't know about the constructor property. Could you shortcut this to var Model = user.constructor? Any particular reason to re-query from the mongoose object? – Brian Jul 16 '13 at 19:38
  • Yes, just `model.constructor.find` is also available. I updated my answer. – Peter Lyons Jul 16 '13 at 19:45
  • 1
    Works great when using promises to resolve a couple of queries at the same time and then find out what actually come back, ie: `Promise.all(promises).then(data => console.log(data[1].constructor.modelName) );`. – Oskar Apr 28 '16 at 06:27