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

Building and Using Models

Pyyhkäise näyttääksesi valikon

After creating a schema, the next step is building a model. A model is created from a schema and provides methods for interacting with documents inside a MongoDB collection.

Models allow you to create, read, update, and delete data using simple JavaScript methods.

Example:

const mongoose = require('mongoose');

// Create the schema
const userSchema = new mongoose.Schema({
  name: String,
  email: String,
  age: Number
});

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

In this example, the User model is connected to the users collection inside MongoDB. Mongoose automatically converts the model name to a collection name.

Creating Documents

Models can be used to create new documents.

Example:

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

newUser.save();

The save() method stores the document in the database.

Querying Documents

Models also provide methods for reading data.

Example:

User.find().then(users => {
  console.log(users);
});

The find() method returns all documents from the collection.

You can also search for specific documents.

Example:

User.findOne({ email: 'alice@example.com' })
  .then(user => {
    console.log(user);
  });

Models make database operations cleaner and easier to manage compared to writing raw MongoDB queries throughout your application.

question mark

Which statements about Mongoose models are correct?

Valitse kaikki oikeat vastaukset

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 2. Luku 2

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

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

Osio 2. Luku 2
some-alt