노드 리액트 기초 강의 #13 mongoose methods statics 차이
in mongoose, I made method using methods and statics. What is the difference?
In Mongoose, the methods
object on a schema is used to add instance methods, which are available on all documents of that schema. In contrast, the statics
object is used to add static methods, which are available on the model itself.
Here's an example of how you might use these two properties to add methods to a schema:
const mongoose = require('mongoose');
const schema = new mongoose.Schema({
name: String,
age: Number
});
// Add an instance method
schema.methods.greet = function() {
console.log(`Hello, my name is ${this.name}`);
}
// Add a static method
schema.statics.findByName = function(name) {
return this.find({ name });
}
const Model = mongoose.model('Model', schema);
const instance = new Model({ name: 'John', age: 20 });
// Use the instance method
instance.greet(); // Output: "Hello, my name is John"
// Use the static method
const john = Model.findByName('John');
As you can see in the example, instance methods are called on individual documents, while static methods are called on the model itself. This is the main difference between the methods
and statics
properties in Mongoose.
when do i use them?
You would use instance methods when you want to add a method that will be available on all documents of a certain schema. For example, you might add an instance method to a User
schema that allows you to generate a password reset token for a user. This method would be called on an individual user document, and would only be available for that user.
You would use static methods when you want to add a method that will be available on the model itself, rather than on individual documents. For example, you might add a static method to a User
schema that allows you to find all users with a certain name. This method would be called on the User
model, and would return an array of all matching users.
In general, you would use instance methods when you want to operate on a single document, and static methods when you want to operate on a collection of documents or the model itself.
댓글을 작성해보세요.