DEV Community

Cover image for How to delete documents in mongo with mongoose
Adrian Matei for Codever

Posted on β€’ Edited on β€’ Originally published at codever.dev

5 2

How to delete documents in mongo with mongoose

To delete one entry you can use findOneAndRemove command - it issues a mongodb findAndModify remove command.
Finds a matching document, removes it, passing the found document (if any) to the callback.

let deleteBookmarkById = async (userId, bookmarkId) => {
  const bookmark = await Bookmark.findOneAndRemove({
    _id: bookmarkId,
    userId: userId
  });

  if ( !bookmark ) {
    throw new NotFoundError('Bookmark NOT_FOUND with id: ' + bookmarkId);
  } else {
    return true;
  }
};
Enter fullscreen mode Exit fullscreen mode

An alternative is to use the deleteOne() method which deletes the first document that matches conditions from the collection. It returns an object with the property deletedCount indicating how many documents were deleted:

let deleteBookmarkById = async (userId, bookmarkId) => {
  const response = await Bookmark.deleteOne({
    _id: bookmarkId,
    userId: userId
  });

  if ( response.deletedCount !== 1 ) {
    throw new NotFoundError('Bookmark NOT_FOUND with id: ' + bookmarkId);
  } else {
    return true;
  }
};
Enter fullscreen mode Exit fullscreen mode

To delete multiple documents use the deleteMany function. This deletes all the documents that match the conditions specified in filter. It returns an object with the property deletedCount containing the number of documents deleted.

/**
 * Delete bookmarks of a user, identified by userId
 */
let deleteBookmarksByUserId = async (userId) => {
  await Bookmark.deleteMany({userId: userId});
  return true;
};
Enter fullscreen mode Exit fullscreen mode


Reference -

https://mongoosejs.com/docs/api/model.html


Shared with ❀️ from Codever. Use πŸ‘‰ copy to mine functionality to add it to your personal snippets collection.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

πŸ‘‹ Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay