Node.js Backend Development Bootcamp · Lekcja

Operacje CRUD z Mongoose

Zaimplementują Państwo operacje Create, Read, Update i Delete za pomocą metod Mongoose do zarządzania danymi.

Lekcja 3 z 411 kroki

Operacje CRUD z Mongoose to bezpłatna lekcja Node.js Backend Development Bootcamp na CoddyKit. To lekcja 3 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Node.js Backend Development Bootcamp, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Node.js Backend Development Bootcamp zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

What is CRUD?

CRUD stands for Create, Read, Update, and Delete. These are the four fundamental operations you perform on data in almost any database application.

Understanding CRUD is key to building interactive applications where users can manage information.

  • Create: Adding new data.
  • Read: Retrieving existing data.
  • Update: Modifying existing data.
  • Delete: Removing data.

Our Sample Mongoose Model

Before we perform CRUD operations, we need a Mongoose model. This model defines the structure of our documents in MongoDB.

We'll use a simple Book model for our examples:

const mongoose = require('mongoose');

const bookSchema = new mongoose.Schema({
  title: String,
  author: String,
  year: Number
});

const Book = mongoose.model('Book', bookSchema);

This Book model will interact with a books collection in our database.

Creating New Documents

The "Create" operation adds new documents to your MongoDB collection. With Mongoose, you can create a new instance of your model and then call its .save() method.

Alternatively, use Model.create() for a simpler approach.

const mongoose = require('mongoose');

const bookSchema = new mongoose.Schema({
  title: String,
  author: String,
  year: Number
});
const Book = mongoose.model('Book', bookSchema);

async function main() {
  await mongoose.connect('mongodb://localhost:27017/coddykit_db');
  console.log('Connected to MongoDB!');

  try {
    const newBook = new Book({
      title: 'The Great Adventure',
      author: 'A. Explorer',
      year: 2023
    });
    await newBook.save();
    console.log('Book created:', newBook.title);

    const anotherBook = await Book.create({
      title: 'Node.js Handbook',
      author: 'J. Developer',
      year: 2022
    });
    console.log('Book created using create():', anotherBook.title);

  } catch (error) {
    console.error('Error creating book:', error);
  } finally {
    await mongoose.disconnect();
    console.log('Disconnected from MongoDB.');
  }
}

main();

Reading All Documents

The "Read" operation retrieves data. To get all documents from a collection, use the Model.find() method without any arguments.

This returns a Mongoose Query object that you can await.

const mongoose = require('mongoose');

const bookSchema = new mongoose.Schema({
  title: String,
  author: String,
  year: Number
});
const Book = mongoose.model('Book', bookSchema);

async function main() {
  await mongoose.connect('mongodb://localhost:27017/coddykit_db');
  console.log('Connected to MongoDB!');

  try {
    // Ensure there are some books to read
    await Book.deleteMany({}); // Clear existing for clean run
    await Book.create([
      { title: 'Book One', author: 'Author A', year: 2000 },
      { title: 'Book Two', author: 'Author B', year: 2010 }
    ]);

    const allBooks = await Book.find();
    console.log('All Books:');
    allBooks.forEach(book => console.log(`- ${book.title} by ${book.author}`));

  } catch (error) {
    console.error('Error reading books:', error);
  } finally {
    await mongoose.disconnect();
    console.log('Disconnected from MongoDB.');
  }
}

main();

Finding Specific Documents

To find documents that match specific criteria, pass a query object to Model.find(). For a single document, use Model.findOne() or Model.findById() if you have its ID.

const mongoose = require('mongoose');

const bookSchema = new mongoose.Schema({
  title: String,
  author: String,
  year: Number
});
const Book = mongoose.model('Book', bookSchema);

async function main() {
  await mongoose.connect('mongodb://localhost:27017/coddykit_db');
  console.log('Connected to MongoDB!');

  try {
    await Book.deleteMany({});
    const book1 = await Book.create({ title: 'Specific Book', author: 'Jane Doe', year: 2015 });
    await Book.create({ title: 'Another Book', author: 'John Smith', year: 2018 });

    const foundBookById = await Book.findById(book1._id);
    console.log('Found by ID:', foundBookById.title);

    const foundBookByTitle = await Book.findOne({ title: 'Another Book' });
    console.log('Found by title:', foundBookByTitle.title);

    const booksByAuthor = await Book.find({ author: 'Jane Doe' });
    console.log('Books by Jane Doe:', booksByAuthor.length);

  } catch (error) {
    console.error('Error finding specific books:', error);
  } finally {
    await mongoose.disconnect();
    console.log('Disconnected from MongoDB.');
  }
}

main();

Updating Documents Easily

The "Update" operation modifies existing documents. Mongoose provides methods like Model.findByIdAndUpdate() and Model.updateOne() for this.

findByIdAndUpdate() is convenient for updating a document by its unique ID.

const mongoose = require('mongoose');

const bookSchema = new mongoose.Schema({
  title: String,
  author: String,
  year: Number
});
const Book = mongoose.model('Book', bookSchema);

async function main() {
  await mongoose.connect('mongodb://localhost:27017/coddykit_db');
  console.log('Connected to MongoDB!');

  try {
    await Book.deleteMany({});
    const createdBook = await Book.create({ title: 'Old Title', author: 'Original Author', year: 2000 });
    console.log('Original Book:', createdBook.title);

    const updatedBook = await Book.findByIdAndUpdate(
      createdBook._id,
      { title: 'New & Improved Title', year: 2024 },
      { new: true } // Return the updated document
    );
    console.log('Updated Book:', updatedBook.title, 'Year:', updatedBook.year);

  } catch (error) {
    console.error('Error updating book:', error);
  } finally {
    await mongoose.disconnect();
    console.log('Disconnected from MongoDB.');
  }
}

main();

Manual Update & Save

Another way to update is to first find the document, modify its properties, and then call its .save() method. This is useful when you need to perform logic on the document before saving.

It triggers Mongoose middleware (like pre-save hooks) unlike `findByIdAndUpdate` by default.

const mongoose = require('mongoose');

const bookSchema = new mongoose.Schema({
  title: String,
  author: String,
  year: Number
});
const Book = mongoose.model('Book', bookSchema);

async function main() {
  await mongoose.connect('mongodb://localhost:27017/coddykit_db');
  console.log('Connected to MongoDB!');

  try {
    await Book.deleteMany({});
    const createdBook = await Book.create({ title: 'To Be Modified', author: 'Someone', year: 2010 });
    console.log('Original Book:', createdBook.title);

    const bookToModify = await Book.findById(createdBook._id);
    if (bookToModify) {
      bookToModify.title = 'Modified Title with Save';
      bookToModify.year = 2011;
      await bookToModify.save();
      console.log('Modified Book:', bookToModify.title, 'Year:', bookToModify.year);
    }

  } catch (error) {
    console.error('Error modifying and saving book:', error);
  } finally {
    await mongoose.disconnect();
    console.log('Disconnected from MongoDB.');
  }
}

main();

Deleting Documents

The "Delete" operation removes documents from your collection. Mongoose offers methods like Model.findByIdAndDelete() and Model.deleteOne() or Model.deleteMany().

Use these carefully as deletions are usually permanent!

const mongoose = require('mongoose');

const bookSchema = new mongoose.Schema({
  title: String,
  author: String,
  year: Number
});
const Book = mongoose.model('Book', bookSchema);

async function main() {
  await mongoose.connect('mongodb://localhost:27017/coddykit_db');
  console.log('Connected to MongoDB!');

  try {
    await Book.deleteMany({});
    const bookToDelete = await Book.create({ title: 'Ephemeral Book', author: 'Ghost', year: 2020 });
    await Book.create({ title: 'Another One', author: 'Someone Else', year: 2021 });
    console.log('Books before delete:', (await Book.find()).length);

    await Book.findByIdAndDelete(bookToDelete._id);
    console.log('Book deleted by ID.');
    console.log('Books after delete:', (await Book.find()).length);

    await Book.deleteOne({ title: 'Another One' });
    console.log('Another book deleted by criteria.');
    console.log('Books after second delete:', (await Book.find()).length);

  } catch (error) {
    console.error('Error deleting book:', error);
  } finally {
    await mongoose.disconnect();
    console.log('Disconnected from MongoDB.');
  }
}

main();

Asynchronous Operations

All Mongoose CRUD operations are asynchronous. This means they don't block the main thread while waiting for the database.

Always use async/await or Promises (.then()/.catch()) to handle their results and potential errors.

Proper error handling ensures your application is robust and user-friendly.

CRUD Quick Check

Consider the following Mongoose model and code snippet:

const userSchema = new mongoose.Schema({
  username: String,
  email: String
});
const User = mongoose.model('User', userSchema);

// ... connection established ...

async function performAction() {
  const newUser = await User.create({ username: 'coder', email: 'coder@example.com' });
  newUser.username = 'pro_coder';
  await newUser.save();
  console.log(newUser.username);
}
performAction();

What will be logged to the console?

CRUD Operations Summary

You've learned the essential CRUD operations with Mongoose!

  • Create: Use new Model().save() or Model.create().
  • Read: Use Model.find(), Model.findOne(), or Model.findById().
  • Update: Use Model.findByIdAndUpdate() or find, modify, then .save().
  • Delete: Use Model.findByIdAndDelete() or Model.deleteOne().

These operations form the backbone of almost any data-driven application.

Bezpłatny start

Ucz się JavaScript dzięki korepetycjom AI — za darmo

Pisz i uruchamiaj kod w przeglądarce, otrzymuj natychmiastową pomoc od korepetytora AI dostępnego 24/7 i kontynuuj naukę w sieci lub w aplikacji.

Kursy
22
Lekcje
92

Często zadawane pytania

Czy lekcja „Operacje CRUD z Mongoose” jest bezpłatna?

Tak — pełny tekst „Operacje CRUD z Mongoose” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Node.js Backend Development Bootcamp, przejdź na CoddyKit PRO. Kurs Node.js Backend Development Bootcamp zawiera 4 lekcji w sumie.

Co nauczysz się w „Operacje CRUD z Mongoose”?

Zaimplementują Państwo operacje Create, Read, Update i Delete za pomocą metod Mongoose do zarządzania danymi. Ćwiczysz Node.js Backend Development Bootcamp z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Node.js Backend Development Bootcamp?

Nie wymagamy żadnego doświadczenia. Node.js Backend Development Bootcamp w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 3 z 4.

Ile czasu zajmuje lekcja „Operacje CRUD z Mongoose”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Node.js Backend Development Bootcamp?

Tak. Każda lekcja Node.js Backend Development Bootcamp zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Łączenie Node.js z MongoDB
  2. Mongoose ODM do modelowania danych
  3. Operacje CRUD z Mongoose
  4. Odpytywanie i filtrowanie danych za pomocą Mongoose
← Powrót do Node.js Backend Development Bootcamp