Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Schema Options and Methods | Defining Schemas and Models
MongoDB and Mongoose Essentials

Schema Options and Methods

Desliza para mostrar el menú

Mongoose schemas support additional configuration through schema options and custom methods. These features help you control document behavior and organize reusable logic inside your models.

Schema options are passed as a second argument when creating a schema.

Example:

const mongoose = require('mongoose');

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

In this example, the timestamps option automatically adds:

  • createdAt;
  • updatedAt.

These fields track when a document was created and last updated.

Adding Schema Methods

Schemas can also include custom methods. Methods allow you to attach reusable functions to documents created from the model.

Example:

userSchema.methods.getGreeting = function () {
  return `Hello, ${this.name}!`;
};

Now every document created with this schema can use the method.

Example:

const user = new User({
  name: 'Alice'
});

console.log(user.getGreeting());

Output:

Hello, Alice!

Custom methods help keep business logic organized and reusable inside your models.

question mark

Which statements about schema options and methods are correct?

Selecciona todas las respuestas correctas

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 2. Capítulo 3

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

Sección 2. Capítulo 3
some-alt