I'm using a few mongoose model instance methods in an attempt to encapsulate some business logic, rather than have is spread around my application. An example:
MySchema.methods.doSomethingAndUpdateCount = function (somedata) {
//Do something to model here using somedata
this.someCount ++;
this.save();
};
I've been looking at this again today though, and I'm not sure this is really good practice. For one thing, it doesn't really give the part of the application that uses this a way to handle errors. Perhaps the problem is the this.save();
- maybe this should not be in the instance method, but rather called by the consumer of the method. So...
this.save();
from the instance method, or do that in consuming code? An instance of a model is called a document. Models are responsible for creating and reading documents from the underlying MongoDB database.
Methods operate on an instance of a model. Statics behave as helper functions only and can perform any action you want, including collection level searching. They aren't tied to an instance of a Model. But methods are also defined on models and work on all the instances of that model.
The mongoose. model() function of the mongoose module is used to create a collection of a particular database of MongoDB.
Mongoose provides 2 ways of doing this, methods and statics. Methods adds an instance method to documents whereas Statics adds static "class" methods to the Models itself. Given the example Animal Model below: var AnimalSchema = mongoose. Schema({ name: String, type: String, hasTail: Boolean }); module.
The general concept is fine, but your instance method should support a callback parameter that you can provide to save as this.save(callback);
so that the client can be notified of errors.
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