- Jan 2024
-
mongoosejs.com mongoosejs.com
-
Instance methods Instances of Models are documents. Documents have many of their own built-in instance methods. We may also define our own custom document instance methods. // define a schema const animalSchema = new Schema({ name: String, type: String }, { // Assign a function to the "methods" object of our animalSchema through schema options. // By following this approach, there is no need to create a separate TS type to define the type of the instance functions. methods: { findSimilarTypes(cb) { return mongoose.model('Animal').find({ type: this.type }, cb); } } }); // Or, assign a function to the "methods" object of our animalSchema animalSchema.methods.findSimilarTypes = function(cb) { return mongoose.model('Animal').find({ type: this.type }, cb); }; Now all of our animal instances have a findSimilarTypes method available to them. const Animal = mongoose.model('Animal', animalSchema); const dog = new Animal({ type: 'dog' }); dog.findSimilarTypes((err, dogs) => { console.log(dogs); // woof }); Overwriting a default mongoose document method may lead to unpredictable results. See this for more details. The example above uses the Schema.methods object directly to save an instance method. You can also use the Schema.method() helper as described here. Do not declare methods using ES6 arrow functions (=>). Arrow functions explicitly prevent binding this, so your method will not have access to the document and the above examples will not work.
Certainly! Let's break down the provided code snippets:
1. What is it and why is it used?
In Mongoose, a schema is a blueprint for defining the structure of documents within a collection. When you define a schema, you can also attach methods to it. These methods become instance methods, meaning they are available on the individual documents (instances) created from that schema.
Instance methods are useful for encapsulating functionality related to a specific document or model instance. They allow you to define custom behavior that can be executed on a specific document. In the given example, the
findSimilarTypes
method is added to instances of theAnimal
model, making it easy to find other animals of the same type.2. Syntax:
Using
methods
object directly in the schema options:javascript const animalSchema = new Schema( { name: String, type: String }, { methods: { findSimilarTypes(cb) { return mongoose.model('Animal').find({ type: this.type }, cb); } } } );
Using
methods
object directly in the schema:javascript animalSchema.methods.findSimilarTypes = function(cb) { return mongoose.model('Animal').find({ type: this.type }, cb); };
Using
Schema.method()
helper:javascript animalSchema.method('findSimilarTypes', function(cb) { return mongoose.model('Animal').find({ type: this.type }, cb); });
3. Explanation in Simple Words with Examples:
Why it's Used:
Imagine you have a collection of animals in your database, and you want to find other animals of the same type. Instead of writing the same logic repeatedly, you can define a method that can be called on each animal instance to find similar types. This helps in keeping your code DRY (Don't Repeat Yourself) and makes it easier to maintain.
Example:
```javascript const mongoose = require('mongoose'); const { Schema } = mongoose;
// Define a schema with a custom instance method const animalSchema = new Schema({ name: String, type: String });
// Add a custom instance method to find similar types animalSchema.methods.findSimilarTypes = function(cb) { return mongoose.model('Animal').find({ type: this.type }, cb); };
// Create the Animal model using the schema const Animal = mongoose.model('Animal', animalSchema);
// Create an instance of Animal const dog = new Animal({ type: 'dog', name: 'Buddy' });
// Use the custom method to find similar types dog.findSimilarTypes((err, similarAnimals) => { console.log(similarAnimals); }); ```
In this example,
findSimilarTypes
is a custom instance method added to theAnimal
schema. When you create an instance of theAnimal
model (e.g., a dog), you can then callfindSimilarTypes
on that instance to find other animals with the same type. The method uses thethis.type
property, which refers to the type of the current animal instance. This allows you to easily reuse the logic for finding similar types across different instances of theAnimal
model.
Tags
Annotators
URL
-
- Aug 2022
-
twitter.com twitter.com
-
(((Howard Forman))). (2022, January 30). New York City Update Cases down 67%. Positive rate down to 3.8%, lowest since 12/12. Hospital census down 33%, lowest since 12/28. New admits lowest since 12/21. Getting closer and closer to pre-Omicron levels. Https://t.co/c6H98PUA0E [Tweet]. @thehowie. https://twitter.com/thehowie/status/1487582265551077387
-
-
twitter.com twitter.com
-
ReconfigBehSci. (2021, December 14). RT @thehowie: BREAKING South Africa: 82% increase in cases, week over week. 34.9% positive rate. Record 7-day average. Not near platea… [Tweet]. @SciBeh. https://twitter.com/SciBeh/status/1470814593610047490
-
-
www.theguardian.com www.theguardian.com
-
Campbell, D., Sabbagh, D., & Devlin, H. (2022, January 7). Military deployed at London hospitals due to Omicron staff shortages. The Guardian. https://www.theguardian.com/world/2022/jan/07/military-deployed-at-london-hospitals-due-to-omicron-staff-shortages
-
-
twitter.com twitter.com
-
ReconfigBehSci on Twitter: “RT @BNODesk: BREAKING: U.S. reports 716,714 new coronavirus cases, setting world record for cases in one day” / Twitter. (n.d.). Retrieved January 7, 2022, from https://twitter.com/SciBeh/status/1478987541332348933
-
-
www.theatlantic.com www.theatlantic.com
-
Kissane, E. (2021, December 23). We’re About to Lose Track of the Pandemic. The Atlantic. https://www.theatlantic.com/ideas/archive/2021/12/were-about-to-lose-track-of-the-pandemic/621097/
-
-
twitter.com twitter.com
-
ReconfigBehSci. (2021, December 16). RT @MadsAlbertsen85: #Omicron update from Denmark. Omicron cases on the 12th of December adjusted up to 20.5% (+2%). Omicron is now having… [Tweet]. @SciBeh. https://twitter.com/SciBeh/status/1471516083819462670
-
-
twitter.com twitter.com
-
ReconfigBehSci on Twitter: “RT @fascinatorfun: Ouch. Norway 4117 new cases is equivalent to over 50k in the U.K. But the kickers are the sheer speed of increase (43%…” / Twitter. (n.d.). Retrieved December 23, 2021, from https://twitter.com/SciBeh/status/1468139950939901952
-
-
twitter.com twitter.com
-
ReconfigBehSci. (2021, December 11). RT @thehowie: BREAKING: South Africa: Week over week increase of only 4.8% today. 16.4% positive rate is near half of recent levels. 36… [Tweet]. @SciBeh. https://twitter.com/SciBeh/status/1469945163615129602
-
-
twitter.com twitter.com
-
ReconfigBehSci. (2021, December 20). RT @thehowie: South Africa Deaths (7 day average) are near double levels of a few weeks ago. They will go up further. They are only 7.5%… [Tweet]. @SciBeh. https://twitter.com/SciBeh/status/1472991477672419334
-
- Jan 2022
-
www.nbcnewyork.com www.nbcnewyork.com
-
Millman • •, Jennifer. ‘NY Pre-Christmas COVID Testing Delivers Record Total Just Shy of 50,000 Cases in Single Day’. NBC New York (blog). Accessed 3 January 2022. https://www.nbcnewyork.com/news/coronavirus/ny-pre-christmas-covid-testing-delivers-record-total-just-shy-of-50000-cases-in-single-day/3468284/.
-
- Oct 2021
-
ourworldindata.org ourworldindata.org
-
Coronavirus Pandemic Data Explorer. (n.d.). Our World in Data. Retrieved March 3, 2021, from https://ourworldindata.org/coronavirus-data-explorer
Tags
- Bolivia
- Argentina
- Djobouti
- Jersey
- map
- Brazil
- Cote d'ivoire
- South Africa
- Papua New Guinea
- Afghanistan
- Austria
- New Zealand
- Jamaica
- Netherlands
- Asia
- Monaco
- Mexico
- Cuba
- Antigua
- Thailand
- Nigeria
- Romania
- Finland
- Latvia
- Sierra Leone
- Haiti
- Taiwan
- Japan
- Lesotho
- Bulgaria
- Europian Union
- Costa Rica
- Suriname
- Maldives
- Guinea-Bissau
- Micronesia
- Iran
- Georgia
- graph
- Bhutan
- Bahamas
- Syria
- Hungary
- Uganda
- Tajikistan
- Vatican
- Belgium
- Estonia
- Africa
- Philipines
- Burundi
- Croatia
- Oman
- Eswatini
- Poland
- Egypt
- Peru
- Malaysia
- Timor
- Dominica
- India
- Congo
- Ecuador
- Samoa
- Jordan
- Cayman Islands
- Qatar
- Zimbabwe
- Palestine
- Tanzania
- Dominician Republic
- Azerbaijan
- Gabon
- Moldova
- Namibia
- Senegal
- North America
- Tunisia
- Cyprus
- Pakistan
- Vietnam
- Eritrea
- data
- Burkina Faso
- Niger
- Andorra
- Sudan
- Anguilla
- Benin
- Colombia
- San Marino
- Portugal
- Venezuela
- Cape Verde
- Indonesia
- Somalia
- Angola
- Bosnia
- Libya
- Madagascar
- is:webpage
- Italy
- Isle of Man
- Switzerland
- Comoros
- Albania
- Liechtenstein
- Fiji
- Guinea
- Oceania
- United Arab Emirates
- Liberia
- Uruguay
- Mashall Islands
- Ireland
- Botswana
- Grenada
- Lithuania
- Honduras
- Yemen
- Democratic Republic of Congo
- Spain
- Greenland
- Bahrain
- Kazakhstan
- lang:en
- Tobago
- Mongolia
- Armenia
- Gambia
- Faeroe Islands
- Laos
- Turkey
- Saint Vincent
- Singapore
- Seychelles
- Israel
- South America
- Kenya
- Ukraine
- Slovenia
- South Sudan
- USA
- vaccine
- Nepal
- Mali
- Belize
- Bermuda
- Lebanon
- Central African Republic
- Zambia
- test
- table
- Chile
- Montenegro
- Northern Cyprus
- Nicaragua
- Kosovo
- Guernsey
- Guatemala
- Chad
- Morocco
- Greece
- Algeria
- Malta
- Gibraltar
- Slovakia
- Guyana
- Russia
- Saint Kitts and Nevis
- Cameroon
- Barbuda
- Kuwait
- Myanmar
- case fatality rate
- Barbados
- Czechia
- Sweden
- Rwanda
- Sri Lanka
- World
- El Salvador
- Uzbekistan
- Mauritania
- Turks and Caicos Islands
- UK
- Germany
- Falkland Islands
- Solomon Islands
- Serbia
- Cambodia
- Europe
- Ghana
- Paraguay
- mortality
- death
- Luxembourg
- Sao Tome and Principe
- Ethiopia
- Equatorial Guinea
- Hong Kong
- Mauritius
- South Korea
- Malawi
- Mozambique
- Saint Lucia
- Australia
- COVID-19
- case
- Herzegovina
- Vanuatu
- France
- Iraq
- chart
- North Macedonia
- Trinidad
- Belarus
- Denmark
- Kyrgyzstan
- China
- Bangladesh
- Norway
- Togo
- Macao
- Iceland
- Grenadines
- Canada
- Saudi Arabia
- Saint Helena
- Panama
Annotators
URL
-
- Aug 2021
-
twitter.com twitter.com
-
Eric Topol. (2021, August 6). @thehowie With test positivity > 22% you can imagine what the real case N is https://t.co/WzFXQtJdcL [Tweet]. @EricTopol. https://twitter.com/EricTopol/status/1423720474484174853
-
-
twitter.com twitter.com
-
(((Howard Forman))). (2021, August 7). Steep drop in UK cases is over. 7-day moving average now back to 26.7K/day and rising. To those who said that this was over, it is not. To those who said that lifting restrictions on July 19th would have no effect, it may well have had effect. Be humble. Too many unknowns. Https://t.co/y0b55gEKAB [Tweet]. @thehowie. https://twitter.com/thehowie/status/1424030928062623755
-
- Jul 2021
-
www.economist.com www.economist.com
-
Tracking covid-19 across the world. (2021, July 4). The Economist. https://www.economist.com/graphic-detail/2021/07/04/covid-19-has-persuaded-americans-to-leave-city-centres
-
- Jun 2021
-
basarat.gitbook.io basarat.gitbook.ioClasses1
-
If an access modifier is not specified it is implicitly public as that matches the convenient nature of JavaScript 🌹.
-
- May 2021
-
www.aier.org www.aier.org
-
Book, J. (n.d.). The Inevitable Yo-Yo Ride of Pandemic Fortresses – AIER. Retrieved 13 May 2021, from https://www.aier.org/article/the-inevitable-yo-yo-ride-of-pandemic-fortresses/
-
- Oct 2020
-
twitter.com twitter.com
-
(((Howard Forman))) on Twitter. (n.d.). Twitter. Retrieved October 12, 2020, from https://twitter.com/thehowie/status/1315418282590121984
-
- Aug 2020
-
covid-19.iza.org covid-19.iza.org
-
COVID-19 and the Labor Market. (n.d.). IZA – Institute of Labor Economics. Retrieved 25 July 2020, from https://covid-19.iza.org/publications/dp13521/
-
-
twitter.com twitter.com
-
Andy Slavitt @ 🏡 on Twitter: “COVID UPDATE July 13: There are successful examples of taking on COVID-19. And there is one story like no others. New York. 1/” / Twitter. (n.d.). Twitter. Retrieved July 17, 2020, from https://twitter.com/ASlavitt/status/1282838738121502720
-
-
covid-19.iza.org covid-19.iza.org
-
Demographic Determinants of Testing Incidence and COVID-19 Infections in New York City Neighborhoods. COVID-19 and the Labor Market. (n.d.). IZA – Institute of Labor Economics. Retrieved August 8, 2020, from https://covid-19.iza.org/publications/dp13152/
-
- Jul 2020
-
www.nationalgeographic.com www.nationalgeographic.com
-
How the new coronavirus surges compare to New York City’s peak. (2020, July 9). Science. https://www.nationalgeographic.com/science/2020/07/how-new-coronavirus-surges-compare-new-york-city-peak-cvd/
-
-
-
Grabar, H. (2020, April 17). Nothing About New York’s Outbreak Was Inevitable. Slate Magazine. https://slate.com/business/2020/04/coronavirus-new-york-city-outbreak-blame.html
-
- Jun 2020
-
www.sciencedirect.com www.sciencedirect.com
-
Rosenberg, E. S., Tesoriero, J. M., Rosenthal, E. M., Chung, R., Barranco, M. A., Styer, L. M., Parker, M. M., John Leung, S.-Y., Morne, J. E., Greene, D., Holtgrave, D. R., Hoefer, D., Kumar, J., Udo, T., Hutton, B., & Zucker, H. A. (2020). Cumulative incidence and diagnosis of SARS-CoV-2 infection in New York. Annals of Epidemiology. https://doi.org/10.1016/j.annepidem.2020.06.004
-
-
www.theguardian.com www.theguardian.com
-
Anderson, C. (2020, June 18). New Zealand reports fresh coronavirus case as more quarantine breaches emerge. The Guardian. https://www.theguardian.com/world/2020/jun/18/new-zealand-coronavirus-defences-under-scrutiny-as-more-breaches-emerge
-