Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Deleting Documents | CRUD Operations with Mongoose
MongoDB and Mongoose Essentials

Deleting Documents

メニューを表示するにはスワイプしてください

When working with MongoDB through Mongoose, you will often need to delete documents from your collections. Mongoose provides several methods for deletion, each suited to different scenarios. Here is a code example illustrating the use of deleteOne(), deleteMany(), and findByIdAndDelete() methods:

// Assume you have a Mongoose model called User

// Delete a single user with a specific condition
User.deleteOne({ email: "user@example.com" })
  .then((result) => {
    // result.deletedCount will be 1 if a document was deleted
    console.log("Deleted one user:", result);
  })
  .catch((err) => console.error(err));

// Delete all users with the role "guest"
User.deleteMany({ role: "guest" })
  .then((result) => {
    // result.deletedCount shows how many documents were deleted
    console.log("Deleted guest users:", result);
  })
  .catch((err) => console.error(err));

// Delete a user by their unique _id
User.findByIdAndDelete("64f1a2b3c4d5e6f7a8b9c0d1")
  .then((deletedUser) => {
    // deletedUser contains the document that was deleted, or null if not found
    console.log("Deleted user by ID:", deletedUser);
  })
  .catch((err) => console.error(err));

You have several options for deleting documents in Mongoose, each designed for a specific use case. The deleteOne() method removes the first document that matches the given filter. For example, if you want to delete a user with a specific email address and you expect only one such user, deleteOne() is appropriate. The deleteMany() method removes all documents matching the filter. Use this when you want to remove multiple documents at once, such as deleting all users with the role "guest." The findByIdAndDelete() method is used when you know the unique _id of the document you want to delete. This method finds the document by its _id and deletes it, returning the deleted document if it existed. Choosing the right method depends on your requirements: use deleteOne() for single, specific deletions by condition, deleteMany() for bulk deletions, and findByIdAndDelete() when you have the document's _id. Always handle the returned result to check whether a document was actually deleted.

question mark

Which Mongoose method should you use if you want to delete all documents matching a certain condition?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 3.  4

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 3.  4
some-alt