Instance methods
// define a schema
const animalSchema = new Schema({ name: String, type: String });
// 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
});
I was reading the docs of mongoose and I'm not able to understand the work of this piece of code. Can anyone explain it to me.
Someone explain flow of this code
CodePudding user response:
Schemas have a field called methods
. In that field you can insert your own functions like so:
animalSchema.methods.nameOfFunction = function() {
// Return something here
// The `this` keyword refers to the instance of the model
// I return the type here
return this.type;
};
Later when you create a instance of the Schema you can use them.
// animalSchema is the Schema we inserted the function into earlier
// create model from instance
const Animal = mongoose.model('Animal', animalSchema);
// Create ab Instance of the model
// the function added to the methods field gets added
// The dog gets created with type 'dog'
const dog = new Animal({ type: 'dog' });
// Now we can call the function
// the `this` in the function referes to `dog`
var result = dog.nameOfFunction();
// Will put out "dog"
console.log(result)
In the example you provided the function added finds all Animals with the same type as the animal created. The cb
argument of the function is a callback. Another function that gets called when mongoose finished searching.
CodePudding user response:
// define a schema
const animalSchema = new Schema({ name: String, type: String });
Define the Animal schema: what fields and features does an animal object have when saved to the database.
// assign a function to the "methods" object of our animalSchema
animalSchema.methods.findSimilarTypes = function(cb) {
return mongoose.model('Animal').find({ type: this.type }, cb);
};
Define that each object created with the animal recipe should also have a method called findSimilarTypes(callback)
.
const Animal = mongoose.model('Animal', animalSchema);
const dog = new Animal({ type: 'dog' });
dog.findSimilarTypes((err, dogs) => {
console.log(dogs); // woof
});
- When you call mongoose.model() on a schema, Mongoose compiles a model for you. This allows you to create new objects that can be saved to the database, but does not save a new object to the database yet.
- Then a new animal object is created, called
dog
. It has type'dog'
Notice thatdog.findSimilarTypes(cb)
also exists, as defined in the schema. - The method is called, and it will return all objects that have the same type as the object
dog
.