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

Creating a Mongoose Schema

Pyyhkäise näyttääksesi valikon

In Mongoose, schemas define the structure of documents inside a MongoDB collection. A schema acts as a blueprint that describes which fields a document should contain, what data types they use, and whether certain fields are required.

Example:

const mongoose = require('mongoose');

// Create a schema for users
const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },

  email: {
    type: String,
    required: true
  },

  age: {
    type: Number
  }
});

// Export the model
module.exports = mongoose.model('User', userSchema);

Understanding Schema Fields

In this schema:

  • name is a required field and must contain a string;
  • email is also required and uses the String type;
  • age uses the Number type but is optional.

The type property defines the expected data type for a field. Common Mongoose types include:

  • String;
  • Number;
  • Boolean;
  • Date;
  • Array.

The required property enables validation. If a required field is missing, Mongoose throws a validation error when trying to save the document.

Schemas help keep your application data organized and predictable, especially in larger projects where consistent document structure is important.

question mark

Which of the following statements about the User schema above are correct?

Valitse kaikki oikeat vastaukset

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 2. Luku 1

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

Osio 2. Luku 1
some-alt