Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get the model from the document in mongoose?

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.

like image 298
Brian Avatar asked Jul 16 '13 18:07

Brian


People also ask

What does the model function from the Mongoose library do?

Model. A Mongoose model is a wrapper on the Mongoose schema. A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.

What does model find return in Mongoose?

The Model. find() function returns an instance of Mongoose's Query class. The Query class represents a raw CRUD operation that you may send to MongoDB. It provides a chainable interface for building up more sophisticated queries. You don't instantiate a Query directly, Customer.

What is an instance of a model in Mongoose?

An instance of a model is called a document. Models are responsible for creating and reading documents from the underlying MongoDB database.

Is a Mongoose model a collection?

A Mongoose model is the compiled version of the schema definition that maps directly to a single document in a MongoDB collection. An instance of a model is called a document. Mongoose models are responsible for querying, creating, updating, and removing documents from the MongoDB database.


1 Answers

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.

like image 81
Peter Lyons Avatar answered Oct 16 '22 06:10

Peter Lyons