Skip to main content

Instance Methods in Mongoose

Instance Methods in Mongoose | Rustcode

Instance Methods in Mongoose

Instance methods in Mongoose allow you to add custom functions to documents created from a schema. These methods operate on individual document instances and are useful for encapsulating behaviors related to the document's data, enabling cleaner and more maintainable code.


What Are Instance Methods?

  • Instance methods are functions attached to a Mongoose document.
  • They operate on the individual document's data and have access to this referencing the document.
  • Useful to encapsulate behaviors or utilities specific to a single document.

Defining Instance Methods

Add methods to your schema's methods object:

const userSchema = new mongoose.Schema({
  name: String,
  email: String
});

// Define instance method
userSchema.methods.sayHello = function() {
  return `Hello, my name is ${this.name}`;
};

const User = mongoose.model('User', userSchema);

Using Instance Methods

Call instance methods on document instances:

const user = new User({ name: 'Alice', email: 'alice@example.com' });

console.log(user.sayHello()); // Output: Hello, my name is Alice
  • Instance methods can also perform async operations if declared async.

Advantages of Instance Methods

  • Encapsulate document-related logic close to data model.
  • Increase code readability and maintainability.
  • Allow reuse of common functionality for documents.
  • Facilitate better object-oriented design in Mongoose.

Quick Reference Table

Aspect Description Example
Instance Method Function attached to document instances (via schema.methods) schema.methods.func = function() { ... }
Access to this Refers to the current document this.name inside method
Usage Called on a document object doc.func()
Async Support Can be async and return promises schema.methods.asyncFunc = async function() { ... }

Best Practices

  • Keep instance methods focused on document-level operations.
  • Use async instance methods for database-related asynchronous tasks.
  • Avoid mutating other documents directly inside instance methods to maintain separation.
  • Document your custom methods clearly for team collaboration.

Conclusion

Instance methods are a powerful feature in Mongoose to add custom logic tied directly to document instances. They help encapsulate behaviors, improve code organization, and allow your documents to have intelligent, reusable functionality. Properly using instance methods enables cleaner and more maintainable Node.js applications with MongoDB.

Comments