Mongoose 'static' methods vs. 'instance' methods












39















I believe this question is similar to this one but the terminology is different. From the Mongoose 4 documentation:




We may also define our own custom document instance methods too.




// define a schema
var animalSchema = new Schema({ name: String, type: String });

// assign a function to the "methods" object of our animalSchema
animalSchema.methods.findSimilarTypes = function (cb) {
return this.model('Animal').find({ type: this.type }, cb);
}



Now all of our animal instances have a findSimilarTypes method available to it.




And then:




Adding static methods to a Model is simple as well. Continuing with our animalSchema:




// assign a function to the "statics" object of our animalSchema
animalSchema.statics.findByName = function (name, cb) {
return this.find({ name: new RegExp(name, 'i') }, cb);
}

var Animal = mongoose.model('Animal', animalSchema);
Animal.findByName('fido', function (err, animals) {
console.log(animals);
});


It seems with static methods each of the animal instances would have the findByName method available to it as well. What are the statics and methods objects in a Schema? What is the difference and why would I use one over the other?










share|improve this question





























    39















    I believe this question is similar to this one but the terminology is different. From the Mongoose 4 documentation:




    We may also define our own custom document instance methods too.




    // define a schema
    var animalSchema = new Schema({ name: String, type: String });

    // assign a function to the "methods" object of our animalSchema
    animalSchema.methods.findSimilarTypes = function (cb) {
    return this.model('Animal').find({ type: this.type }, cb);
    }



    Now all of our animal instances have a findSimilarTypes method available to it.




    And then:




    Adding static methods to a Model is simple as well. Continuing with our animalSchema:




    // assign a function to the "statics" object of our animalSchema
    animalSchema.statics.findByName = function (name, cb) {
    return this.find({ name: new RegExp(name, 'i') }, cb);
    }

    var Animal = mongoose.model('Animal', animalSchema);
    Animal.findByName('fido', function (err, animals) {
    console.log(animals);
    });


    It seems with static methods each of the animal instances would have the findByName method available to it as well. What are the statics and methods objects in a Schema? What is the difference and why would I use one over the other?










    share|improve this question



























      39












      39








      39


      18






      I believe this question is similar to this one but the terminology is different. From the Mongoose 4 documentation:




      We may also define our own custom document instance methods too.




      // define a schema
      var animalSchema = new Schema({ name: String, type: String });

      // assign a function to the "methods" object of our animalSchema
      animalSchema.methods.findSimilarTypes = function (cb) {
      return this.model('Animal').find({ type: this.type }, cb);
      }



      Now all of our animal instances have a findSimilarTypes method available to it.




      And then:




      Adding static methods to a Model is simple as well. Continuing with our animalSchema:




      // assign a function to the "statics" object of our animalSchema
      animalSchema.statics.findByName = function (name, cb) {
      return this.find({ name: new RegExp(name, 'i') }, cb);
      }

      var Animal = mongoose.model('Animal', animalSchema);
      Animal.findByName('fido', function (err, animals) {
      console.log(animals);
      });


      It seems with static methods each of the animal instances would have the findByName method available to it as well. What are the statics and methods objects in a Schema? What is the difference and why would I use one over the other?










      share|improve this question
















      I believe this question is similar to this one but the terminology is different. From the Mongoose 4 documentation:




      We may also define our own custom document instance methods too.




      // define a schema
      var animalSchema = new Schema({ name: String, type: String });

      // assign a function to the "methods" object of our animalSchema
      animalSchema.methods.findSimilarTypes = function (cb) {
      return this.model('Animal').find({ type: this.type }, cb);
      }



      Now all of our animal instances have a findSimilarTypes method available to it.




      And then:




      Adding static methods to a Model is simple as well. Continuing with our animalSchema:




      // assign a function to the "statics" object of our animalSchema
      animalSchema.statics.findByName = function (name, cb) {
      return this.find({ name: new RegExp(name, 'i') }, cb);
      }

      var Animal = mongoose.model('Animal', animalSchema);
      Animal.findByName('fido', function (err, animals) {
      console.log(animals);
      });


      It seems with static methods each of the animal instances would have the findByName method available to it as well. What are the statics and methods objects in a Schema? What is the difference and why would I use one over the other?







      node.js mongodb mongoose






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited May 23 '17 at 12:26









      Community

      11




      11










      asked Apr 16 '15 at 2:49









      StartecStartec

      4,00095190




      4,00095190
























          2 Answers
          2






          active

          oldest

          votes


















          53














          statics are the methods defined on the Model. methods are defined on the document (instance).



          You might do



          Animal.findByName('fido', function(err, fido){
          // fido => { name: 'fido', type: 'dog' }
          });


          And then you might use the document instance fido to do



          fido.findSimilarTypes(function(err, dogs){
          // dogs => [ {name:'fido',type:'dog} , {name:'sheeba',type:'dog'} ]
          });





          share|improve this answer


























          • So the only usage difference is whether you use the Model or the document to call the method?

            – Startec
            Apr 16 '15 at 3:03






          • 7





            You can't use Animals.findSimilarTypes because Animals is a model, it has no "type". findSimilarTypes needs a this.type which wouldn't exist in Animals model, only a document instance would contain that property, as defined in the model.

            – laggingreflex
            Apr 16 '15 at 3:06








          • 2





            Similarly you can't do fido.findByName because findByName would need to search through all documents and fido is just a document.

            – laggingreflex
            Apr 16 '15 at 3:07






          • 1





            @laggingreflex Your second comment is not true. You could have fido.findByName, since fido does have access to the entire collection (via this.model('Animal')). However, it doesn't make much sense to have an instance method that doesn't use any properties from the instance.

            – Aaron Dufour
            Apr 16 '15 at 4:13






          • 1





            @UdayHiwarale this.constructor

            – laggingreflex
            Jul 9 '16 at 16:22





















          0














          Database logic should be encapsulated within the data model. 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.The static keyword defines a static method for a model. Static methods aren't called on instances of the model. Instead, they're called on the model itself. These are often utility functions, such as functions to create or clone objects. like example below:



          const bookSchema = mongoose.Schema({
          title: {
          type : String,
          required : [true, 'Book name required']
          },
          publisher : {
          type : String,
          required : [true, 'Publisher name required']
          },
          thumbnail : {
          type : String
          }
          type : {
          type : String
          },
          hasAward : {
          type : Boolean
          }
          });

          //method
          bookSchema.methods.findByType = function (callback) {
          return this.model('Book').find({ type: this.type }, callback);
          };

          // statics
          bookSchema.statics.findBooksWithAward = function (callback) {
          Book.find({ hasAward: true }, callback);
          };

          const Book = mongoose.model('Book', bookSchema);
          export default Book;


          for more info: https://osmangoni.info/posts/separating-methods-schema-statics-mongoose/






          share|improve this answer
























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f29664499%2fmongoose-static-methods-vs-instance-methods%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            53














            statics are the methods defined on the Model. methods are defined on the document (instance).



            You might do



            Animal.findByName('fido', function(err, fido){
            // fido => { name: 'fido', type: 'dog' }
            });


            And then you might use the document instance fido to do



            fido.findSimilarTypes(function(err, dogs){
            // dogs => [ {name:'fido',type:'dog} , {name:'sheeba',type:'dog'} ]
            });





            share|improve this answer


























            • So the only usage difference is whether you use the Model or the document to call the method?

              – Startec
              Apr 16 '15 at 3:03






            • 7





              You can't use Animals.findSimilarTypes because Animals is a model, it has no "type". findSimilarTypes needs a this.type which wouldn't exist in Animals model, only a document instance would contain that property, as defined in the model.

              – laggingreflex
              Apr 16 '15 at 3:06








            • 2





              Similarly you can't do fido.findByName because findByName would need to search through all documents and fido is just a document.

              – laggingreflex
              Apr 16 '15 at 3:07






            • 1





              @laggingreflex Your second comment is not true. You could have fido.findByName, since fido does have access to the entire collection (via this.model('Animal')). However, it doesn't make much sense to have an instance method that doesn't use any properties from the instance.

              – Aaron Dufour
              Apr 16 '15 at 4:13






            • 1





              @UdayHiwarale this.constructor

              – laggingreflex
              Jul 9 '16 at 16:22


















            53














            statics are the methods defined on the Model. methods are defined on the document (instance).



            You might do



            Animal.findByName('fido', function(err, fido){
            // fido => { name: 'fido', type: 'dog' }
            });


            And then you might use the document instance fido to do



            fido.findSimilarTypes(function(err, dogs){
            // dogs => [ {name:'fido',type:'dog} , {name:'sheeba',type:'dog'} ]
            });





            share|improve this answer


























            • So the only usage difference is whether you use the Model or the document to call the method?

              – Startec
              Apr 16 '15 at 3:03






            • 7





              You can't use Animals.findSimilarTypes because Animals is a model, it has no "type". findSimilarTypes needs a this.type which wouldn't exist in Animals model, only a document instance would contain that property, as defined in the model.

              – laggingreflex
              Apr 16 '15 at 3:06








            • 2





              Similarly you can't do fido.findByName because findByName would need to search through all documents and fido is just a document.

              – laggingreflex
              Apr 16 '15 at 3:07






            • 1





              @laggingreflex Your second comment is not true. You could have fido.findByName, since fido does have access to the entire collection (via this.model('Animal')). However, it doesn't make much sense to have an instance method that doesn't use any properties from the instance.

              – Aaron Dufour
              Apr 16 '15 at 4:13






            • 1





              @UdayHiwarale this.constructor

              – laggingreflex
              Jul 9 '16 at 16:22
















            53












            53








            53







            statics are the methods defined on the Model. methods are defined on the document (instance).



            You might do



            Animal.findByName('fido', function(err, fido){
            // fido => { name: 'fido', type: 'dog' }
            });


            And then you might use the document instance fido to do



            fido.findSimilarTypes(function(err, dogs){
            // dogs => [ {name:'fido',type:'dog} , {name:'sheeba',type:'dog'} ]
            });





            share|improve this answer















            statics are the methods defined on the Model. methods are defined on the document (instance).



            You might do



            Animal.findByName('fido', function(err, fido){
            // fido => { name: 'fido', type: 'dog' }
            });


            And then you might use the document instance fido to do



            fido.findSimilarTypes(function(err, dogs){
            // dogs => [ {name:'fido',type:'dog} , {name:'sheeba',type:'dog'} ]
            });






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Apr 16 '15 at 3:04

























            answered Apr 16 '15 at 3:02









            laggingreflexlaggingreflex

            14.9k1996150




            14.9k1996150













            • So the only usage difference is whether you use the Model or the document to call the method?

              – Startec
              Apr 16 '15 at 3:03






            • 7





              You can't use Animals.findSimilarTypes because Animals is a model, it has no "type". findSimilarTypes needs a this.type which wouldn't exist in Animals model, only a document instance would contain that property, as defined in the model.

              – laggingreflex
              Apr 16 '15 at 3:06








            • 2





              Similarly you can't do fido.findByName because findByName would need to search through all documents and fido is just a document.

              – laggingreflex
              Apr 16 '15 at 3:07






            • 1





              @laggingreflex Your second comment is not true. You could have fido.findByName, since fido does have access to the entire collection (via this.model('Animal')). However, it doesn't make much sense to have an instance method that doesn't use any properties from the instance.

              – Aaron Dufour
              Apr 16 '15 at 4:13






            • 1





              @UdayHiwarale this.constructor

              – laggingreflex
              Jul 9 '16 at 16:22





















            • So the only usage difference is whether you use the Model or the document to call the method?

              – Startec
              Apr 16 '15 at 3:03






            • 7





              You can't use Animals.findSimilarTypes because Animals is a model, it has no "type". findSimilarTypes needs a this.type which wouldn't exist in Animals model, only a document instance would contain that property, as defined in the model.

              – laggingreflex
              Apr 16 '15 at 3:06








            • 2





              Similarly you can't do fido.findByName because findByName would need to search through all documents and fido is just a document.

              – laggingreflex
              Apr 16 '15 at 3:07






            • 1





              @laggingreflex Your second comment is not true. You could have fido.findByName, since fido does have access to the entire collection (via this.model('Animal')). However, it doesn't make much sense to have an instance method that doesn't use any properties from the instance.

              – Aaron Dufour
              Apr 16 '15 at 4:13






            • 1





              @UdayHiwarale this.constructor

              – laggingreflex
              Jul 9 '16 at 16:22



















            So the only usage difference is whether you use the Model or the document to call the method?

            – Startec
            Apr 16 '15 at 3:03





            So the only usage difference is whether you use the Model or the document to call the method?

            – Startec
            Apr 16 '15 at 3:03




            7




            7





            You can't use Animals.findSimilarTypes because Animals is a model, it has no "type". findSimilarTypes needs a this.type which wouldn't exist in Animals model, only a document instance would contain that property, as defined in the model.

            – laggingreflex
            Apr 16 '15 at 3:06







            You can't use Animals.findSimilarTypes because Animals is a model, it has no "type". findSimilarTypes needs a this.type which wouldn't exist in Animals model, only a document instance would contain that property, as defined in the model.

            – laggingreflex
            Apr 16 '15 at 3:06






            2




            2





            Similarly you can't do fido.findByName because findByName would need to search through all documents and fido is just a document.

            – laggingreflex
            Apr 16 '15 at 3:07





            Similarly you can't do fido.findByName because findByName would need to search through all documents and fido is just a document.

            – laggingreflex
            Apr 16 '15 at 3:07




            1




            1





            @laggingreflex Your second comment is not true. You could have fido.findByName, since fido does have access to the entire collection (via this.model('Animal')). However, it doesn't make much sense to have an instance method that doesn't use any properties from the instance.

            – Aaron Dufour
            Apr 16 '15 at 4:13





            @laggingreflex Your second comment is not true. You could have fido.findByName, since fido does have access to the entire collection (via this.model('Animal')). However, it doesn't make much sense to have an instance method that doesn't use any properties from the instance.

            – Aaron Dufour
            Apr 16 '15 at 4:13




            1




            1





            @UdayHiwarale this.constructor

            – laggingreflex
            Jul 9 '16 at 16:22







            @UdayHiwarale this.constructor

            – laggingreflex
            Jul 9 '16 at 16:22















            0














            Database logic should be encapsulated within the data model. 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.The static keyword defines a static method for a model. Static methods aren't called on instances of the model. Instead, they're called on the model itself. These are often utility functions, such as functions to create or clone objects. like example below:



            const bookSchema = mongoose.Schema({
            title: {
            type : String,
            required : [true, 'Book name required']
            },
            publisher : {
            type : String,
            required : [true, 'Publisher name required']
            },
            thumbnail : {
            type : String
            }
            type : {
            type : String
            },
            hasAward : {
            type : Boolean
            }
            });

            //method
            bookSchema.methods.findByType = function (callback) {
            return this.model('Book').find({ type: this.type }, callback);
            };

            // statics
            bookSchema.statics.findBooksWithAward = function (callback) {
            Book.find({ hasAward: true }, callback);
            };

            const Book = mongoose.model('Book', bookSchema);
            export default Book;


            for more info: https://osmangoni.info/posts/separating-methods-schema-statics-mongoose/






            share|improve this answer




























              0














              Database logic should be encapsulated within the data model. 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.The static keyword defines a static method for a model. Static methods aren't called on instances of the model. Instead, they're called on the model itself. These are often utility functions, such as functions to create or clone objects. like example below:



              const bookSchema = mongoose.Schema({
              title: {
              type : String,
              required : [true, 'Book name required']
              },
              publisher : {
              type : String,
              required : [true, 'Publisher name required']
              },
              thumbnail : {
              type : String
              }
              type : {
              type : String
              },
              hasAward : {
              type : Boolean
              }
              });

              //method
              bookSchema.methods.findByType = function (callback) {
              return this.model('Book').find({ type: this.type }, callback);
              };

              // statics
              bookSchema.statics.findBooksWithAward = function (callback) {
              Book.find({ hasAward: true }, callback);
              };

              const Book = mongoose.model('Book', bookSchema);
              export default Book;


              for more info: https://osmangoni.info/posts/separating-methods-schema-statics-mongoose/






              share|improve this answer


























                0












                0








                0







                Database logic should be encapsulated within the data model. 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.The static keyword defines a static method for a model. Static methods aren't called on instances of the model. Instead, they're called on the model itself. These are often utility functions, such as functions to create or clone objects. like example below:



                const bookSchema = mongoose.Schema({
                title: {
                type : String,
                required : [true, 'Book name required']
                },
                publisher : {
                type : String,
                required : [true, 'Publisher name required']
                },
                thumbnail : {
                type : String
                }
                type : {
                type : String
                },
                hasAward : {
                type : Boolean
                }
                });

                //method
                bookSchema.methods.findByType = function (callback) {
                return this.model('Book').find({ type: this.type }, callback);
                };

                // statics
                bookSchema.statics.findBooksWithAward = function (callback) {
                Book.find({ hasAward: true }, callback);
                };

                const Book = mongoose.model('Book', bookSchema);
                export default Book;


                for more info: https://osmangoni.info/posts/separating-methods-schema-statics-mongoose/






                share|improve this answer













                Database logic should be encapsulated within the data model. 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.The static keyword defines a static method for a model. Static methods aren't called on instances of the model. Instead, they're called on the model itself. These are often utility functions, such as functions to create or clone objects. like example below:



                const bookSchema = mongoose.Schema({
                title: {
                type : String,
                required : [true, 'Book name required']
                },
                publisher : {
                type : String,
                required : [true, 'Publisher name required']
                },
                thumbnail : {
                type : String
                }
                type : {
                type : String
                },
                hasAward : {
                type : Boolean
                }
                });

                //method
                bookSchema.methods.findByType = function (callback) {
                return this.model('Book').find({ type: this.type }, callback);
                };

                // statics
                bookSchema.statics.findBooksWithAward = function (callback) {
                Book.find({ hasAward: true }, callback);
                };

                const Book = mongoose.model('Book', bookSchema);
                export default Book;


                for more info: https://osmangoni.info/posts/separating-methods-schema-statics-mongoose/







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Aug 19 '18 at 23:18









                MR EXCELMR EXCEL

                12




                12






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f29664499%2fmongoose-static-methods-vs-instance-methods%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    How to pass form data using jquery Ajax to insert data in database?

                    National Museum of Racing and Hall of Fame

                    Guess what letter conforming each word