Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose - instance methods updating the model, is this good practice?

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...

  • Is it good practice to have instance methods that update the instance data?
  • If so, should you call this.save(); from the instance method, or do that in consuming code?
  • How are you supposed to handle errors in this scenario?
like image 925
UpTheCreek Avatar asked Aug 16 '12 11:08

UpTheCreek


People also ask

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.

What is the difference between methods and statics Mongoose?

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.

Is Mongoose model a collection?

The mongoose. model() function of the mongoose module is used to create a collection of a particular database of MongoDB.

What is method in Mongoose?

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.


1 Answers

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.

like image 143
JohnnyHK Avatar answered Nov 15 '22 05:11

JohnnyHK