Models is a constructor that is compiled from the Schema definition. Examples of these model represent documents that can be stored and retrieved from the database. All document creation and retrieval in the database is handled by these model.
1. Compile the first model
var New Mongoose. Schema ({name: ' string ', Size: ' String ' }); var Tank = Mongoose.model (' Tank ', schema);
The first parameter is the singular name of the model corresponding to the collection. Mongoose automatically finds the plural version of the model name. therefore, as in the example above, model tank corresponds to tanks collection in the database. The model () function uses a schema to make a copy. Make sure you have added all the things you want to the schema before calling model ().
2. Build the document
Documents is an example of model. It's easy to create them and save them to the database.
varTank = Mongoose.model (' Tank '), Yourschema);varsmall =NewTank ({size: ' small '}); Small.save (function(err) {if(ERR)returnHandleError (ERR); //saved!})//ortank.create ({size:' Small '},function(err, small) {if(ERR)returnHandleError (ERR); //saved!})
Note that no tanks will be created/deleted until you connect to the model using open. In this case we use Mongoose.model (), we open the default Mongoose collection.
Mongoose.connect (' localhost ', ' gettingstarted ');
3. Enquiry
Querying document with Mongoose is easy, and it supports MongoDB's rich query syntax. Documents can be retrieved using each model method (find, FindByID, FindOne) or a static method (where).
Tank.find ({size: ' small '}). where (' CreatedDate '). GT (Oneyearago). exec (callback);
See the querying section for details on how to use the query API.
4. Delete
Model has a static Delete method that can be used to delete all document matching criteria.
function (Err) { ifreturn handleError (err); // removed!});
5. Modification
Each model has its own modification method to modify the document in the database without returning to your application. View the more detailed API documentation.
If you want to modify a document in DB and return it to your application, use Findoneandupdate.
6. More
API documentation includes the need for additional methods available like Count, MapReduce, aggregate, etc.
Mongoose Document (ii) Models