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.
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.
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.
An instance of a model is called a document. Models are responsible for creating and reading documents from the underlying MongoDB database.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With