findone and delete mongoose code example

Example 1: findoneanddelete mongoose

// Find only one document matching the
// condition(age >= 5) and delete it
User.findOneAndDelete({age: {$gte:5} }, function (err, docs) {
    if (err){
        console.log(err)
    }
    else{
        console.log("Deleted User : ", docs);
    }
});

Example 2: mongoose find by and delete

Campground.findByIdAndRemove(req.params.id, function(err){
      if(err){
          res.redirect("/campgrounds");
      } else {
          res.redirect("/campgrounds");
      }
   });

Example 3: deleteOne mongoose

Tank.deleteOne({ size: 'large' }, function (err) {
  if (err) return handleError(err);
  // deleted at most one tank document
});

Example 4: delete document mongose

Model.deleteOne({ options }, function (err) {});

Example 5: mongoose remove data

Remove is deprecated - use delete
Update for Mongoose v5.5.3 - remove() is now deprecated.
Use deleteOne(), deleteMany() or findOneAndDelete() instead.