2

Am I wrong if I say that this code is not clear?

I understand more or less what this should do but... I guess that we are looking at objects that have the same type in a collection?

The things are the way they wrote this code sounds not really clear for me. Can you please provide a better example or correct this one?

Many thanks

https://mongoosejs.com/docs/guide.html

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

 var Animal = mongoose.model('Animal', animalSchema);
 var dog = new Animal({ type: 'dog' });

 dog.findSimilarTypes(function(err, dogs) {
   console.log(dogs); // woof
 });
FZs
  • 16,581
  • 13
  • 41
  • 50
Mo Adam
  • 21
  • 1
  • Possible duplicate of [Mongoose 'static' methods vs. 'instance' methods](https://stackoverflow.com/questions/29664499/mongoose-static-methods-vs-instance-methods) – laggingreflex Oct 12 '19 at 04:09

2 Answers2

1

A Mongoose modelschema declaration is more or less like a Class declaration, so it's more or less like this:

    class Person {
        constructor (name, yearOfBirth, job) {
            this.name = name;
            this.yearOfBirth = yearOfBirth;
            this.job = job;
        }

        calculateAge() {
            var age = new Date().getFullYear - this.yearOfBirth;
            console.log(age);
        }
    }

    const john6 = new Person6('John', 1990, 'teacher');

john6.calculateAge() // Returns age
halfer
  • 19,824
  • 17
  • 99
  • 186
Mattia Rasulo
  • 1,236
  • 10
  • 15
0

It seems the docs have a very unintuitive way of explaining things. Let's go over the basics of creating a model, shall we? You define a schema -

var mongoose = require('mongoose');
  var Schema = mongoose.Schema;
  // any random Schema
  var animal_SCHEMA = new Schema({
    name:  String,
    type: String
  });

You can define your own methods that your model instances can use.

Taking the example from the docs, the way to create an instance method is -

animalSchema.methods.findSimilarTypes = function() {
    return mongoose.model('Animal').find({ type: this.type }); //I omitted the callback for simplicity
  };

Then, you make a model and may export it. Here I'm just creating the model.

var animal_MODEL = mongoose.model('Animals', animal_SCHEMA);

So now you created a model and an instance instance for the model instances, but where's the instance that will use it? Let's create one. This is how you normally create an instance of your model. Nothing new about it.

var newAnimal = new animal_MODEL({name:"Scobby", type:"Detective"}); // this can use findSimilarTypes

You're probably comfortable to create such new instances and save them, usually like -

const savedData = await newAnimal.save();

Ever wondered about the save() method? Well, that's an example of an instance method! Mongoose supplies save() by default along with a bunch of other methods, see the API docs.

They are called so because they only come with an instance of an object.

Every instance of a model you create has some built-in instance methods. The one you defined earlier, that's an instance method that is custom and made by you. Now, newAnimal can use this method.

In fact, all new instances you spawn for this model will have access to the findSimilarTypes method.

var badAnimal = new animal_MODEL({name:"Scrappy", type:"Trouble Maker"});
var trouble_makers = badAnimal.findSimilarTypes();
console.log(trouble_makers);
ak_linus
  • 532
  • 4
  • 6