Bird
Raised Fist0
Expressframework~10 mins

Deleting documents in Express - Interactive Code Practice

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to delete a document by ID using Express and Mongoose.

Express
app.delete('/items/:id', async (req, res) => {
  try {
    await Item.[1](req.params.id);
    res.send('Deleted successfully');
  } catch (error) {
    res.status(500).send(error.message);
  }
});
Drag options to blanks, or click blank then click option'
AfindByIdAndDelete
BdeleteOneById
CremoveById
DdeleteById
Attempts:
3 left
💡 Hint
Common Mistakes
Using a method that does not exist like 'removeById'.
Trying to delete without specifying the ID.
2fill in blank
medium

Complete the code to send a 404 status if the document to delete is not found.

Express
app.delete('/users/:id', async (req, res) => {
  const deletedUser = await User.findByIdAndDelete(req.params.id);
  if (![1]) {
    return res.status(404).send('User not found');
  }
  res.send('User deleted');
});
Drag options to blanks, or click blank then click option'
Areq.params.id
BdeletedUser
CUser
Dres
Attempts:
3 left
💡 Hint
Common Mistakes
Checking req.params.id instead of the deleted document.
Not handling the case when the document is not found.
3fill in blank
hard

Fix the error in the code to delete a document using Express and Mongoose.

Express
app.delete('/posts/:id', async (req, res) => {
  try {
    const result = await Post.[1]({ _id: req.params.id });
    if (result.deletedCount === 0) {
      return res.status(404).send('Post not found');
    }
    res.send('Post deleted');
  } catch (err) {
    res.status(500).send(err.message);
  }
});
Drag options to blanks, or click blank then click option'
AdeleteOne
Bremove
CfindByIdAndDelete
DdeleteMany
Attempts:
3 left
💡 Hint
Common Mistakes
Using remove which is deprecated.
Using findByIdAndDelete which returns the deleted document, not a result with deletedCount.
4fill in blank
hard

Fill both blanks to delete multiple documents matching a condition and send the count of deleted documents.

Express
app.delete('/tasks/completed', async (req, res) => {
  const result = await Task.[1]({ completed: true });
  res.send(`Deleted [2] completed tasks`);
});
Drag options to blanks, or click blank then click option'
AdeleteMany
Bcount
Cresult.deletedCount
Dfind
Attempts:
3 left
💡 Hint
Common Mistakes
Using find which only retrieves documents.
Trying to use count instead of deletedCount.
5fill in blank
hard

Fill all three blanks to delete a document by ID, handle errors, and send appropriate responses.

Express
app.delete('/comments/:id', async (req, res) => {
  try {
    const deleted = await Comment.[1](req.params.id);
    if (![2]) {
      return res.status(404).send('Comment not found');
    }
    res.[3]('Comment deleted');
  } catch (error) {
    res.status(500).send(error.message);
  }
});
Drag options to blanks, or click blank then click option'
AfindByIdAndDelete
Bdeleted
Csend
DdeleteOne
Attempts:
3 left
💡 Hint
Common Mistakes
Using deleteOne with ID directly (needs filter object).
Checking the wrong variable for deletion result.
Using res.sendStatus instead of res.send for success message.

Practice

(1/5)
1. What does the deleteOne() method do in Express when working with a database?
easy
A. Deletes a single document that matches the filter criteria.
B. Deletes all documents in the collection.
C. Updates a document instead of deleting it.
D. Finds a document but does not delete it.

Solution

  1. Step 1: Understand deleteOne() purpose

    The deleteOne() method removes only one document that matches the given filter.
  2. Step 2: Compare with other methods

    deleteMany() deletes multiple documents, and find() only retrieves data without deleting.
  3. Final Answer:

    Deletes a single document that matches the filter criteria. -> Option A
  4. Quick Check:

    deleteOne() = deletes one document [OK]
Hint: Remember: deleteOne removes just one matching document [OK]
Common Mistakes:
  • Confusing deleteOne with deleteMany
  • Thinking deleteOne updates documents
  • Assuming deleteOne finds but does not delete
2. Which of the following is the correct syntax to delete a document by its ID using Mongoose in Express?
easy
A. Model.findByIdAndDelete(id, callback);
B. Model.deleteById(id);
C. Model.removeById(id);
D. Model.deleteOneById(id);

Solution

  1. Step 1: Recall Mongoose method for deleting by ID

    The correct method is findByIdAndDelete() which deletes a document by its ID.
  2. Step 2: Check syntax correctness

    Only Model.findByIdAndDelete(id, callback); matches the official Mongoose syntax.
  3. Final Answer:

    Model.findByIdAndDelete(id, callback); -> Option A
  4. Quick Check:

    Use findByIdAndDelete to delete by ID [OK]
Hint: Use findByIdAndDelete to remove by ID [OK]
Common Mistakes:
  • Using non-existent methods like deleteById
  • Confusing deleteOne with findByIdAndDelete
  • Missing callback or async handling
3. What will be the output of this code snippet in Express using Mongoose?
Model.deleteMany({ status: 'inactive' })
  .then(result => console.log(result.deletedCount))
  .catch(err => console.error(err));
medium
A. An error because deleteMany does not return deletedCount.
B. The entire deleted documents array.
C. Number of documents deleted with status 'inactive'.
D. Undefined because deleteMany returns nothing.

Solution

  1. Step 1: Understand deleteMany return value

    deleteMany() returns an object with deletedCount indicating how many documents were deleted.
  2. Step 2: Analyze the console.log statement

    The code logs result.deletedCount, so it outputs the number of deleted documents matching the filter.
  3. Final Answer:

    Number of documents deleted with status 'inactive'. -> Option C
  4. Quick Check:

    deleteMany() returns deletedCount [OK]
Hint: deleteMany returns deletedCount in result object [OK]
Common Mistakes:
  • Expecting deleted documents array
  • Assuming deleteMany returns nothing
  • Confusing deletedCount with total documents
4. Identify the error in this Express Mongoose code snippet for deleting a document:
Model.deleteOne({ _id: id }, (err, doc) => {
  if (err) console.log(err);
  else console.log(doc);
});
medium
A. The filter object is missing required fields.
B. The deleteOne method does not accept a callback.
C. The method should be deleteMany to delete one document.
D. The callback parameter doc should be result to access deletion info.

Solution

  1. Step 1: Check callback parameters for deleteOne

    The second callback parameter is a result object, not the deleted document itself.
  2. Step 2: Understand what doc represents

    It should be named result or similar to reflect it contains deletion info like deletedCount, not the document.
  3. Final Answer:

    The callback parameter doc should be result to access deletion info. -> Option D
  4. Quick Check:

    Callback gets result info, not deleted doc [OK]
Hint: Callback second param is result info, not deleted doc [OK]
Common Mistakes:
  • Expecting deleted document in callback
  • Using deleteMany when only one document needed
  • Assuming deleteOne does not accept callbacks
5. You want to delete all documents where the field active is false, but only if the user confirms. Which Express code snippet correctly handles this with error checking?
hard
A. Model.deleteMany({ active: false }, (err, res) => { if (err) throw err; console.log(res); });
B. if(confirm) { Model.deleteMany({ active: false }) .then(res => console.log(`${res.deletedCount} deleted`)) .catch(err => console.error(err)); }
C. if(confirm) { Model.deleteOne({ active: false }) .then(res => console.log(res)) .catch(err => console.error(err)); }
D. Model.deleteMany({ active: false }) .then(res => console.log(res.deletedCount)) .catch(err => console.error(err));

Solution

  1. Step 1: Check user confirmation before deleting

    if(confirm) { Model.deleteMany({ active: false }) .then(res => console.log(`${res.deletedCount} deleted`)) .catch(err => console.error(err)); } uses an if(confirm) check to ensure deletion only happens after user confirmation.
  2. Step 2: Verify deletion and error handling

    It uses deleteMany to delete all matching documents, logs the count, and catches errors properly.
  3. Final Answer:

    if(confirm) { Model.deleteMany({ active: false }) .then(res => console.log(`${res.deletedCount} deleted`)) .catch(err => console.error(err)); } -> Option B
  4. Quick Check:

    Confirm before delete, handle errors [OK]
Hint: Check confirm before deleteMany, handle errors in promise [OK]
Common Mistakes:
  • Using deleteOne instead of deleteMany for multiple docs
  • Not checking user confirmation before deleting
  • Throwing errors instead of catching them