Simple
Simple

Reputation: 437

Why are documents not being deleted from the mongodb database?

I'm trying to delete a document form the mongodb database but it isn't working. I don't understand why because the console doesn't give any errors and displays the query object properly. However, when I view the database the respective document is still there.

URL
http://localhost:7000/delete/5c641f44923cf17c1cfe1002

Console

{ _id: '5c641f44923cf17c1cfe1002' }
1 document deleted

Server.js:

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });

const MongoClient = require('mongodb').MongoClient;



app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());
// Connection URL
const url = "mongodb://localhost:27017/DataBaseName";

app.listen(7000);

app.set('view engine', 'ejs');

// Express routes

//Default routes
app.get('/', function(req, res){

    MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
        if (err) throw err;
        var dbo = db.db("DataBaseName");
        dbo.collection("customers").find({}).toArray(function(err, result) {
            if (err) throw err;
            console.log(db);
            db.close();
            res.render('index', {result:result});
        });
    });
});
//Submit button route
app.post('/submitData',urlencodedParser,function(req, res){

    MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
      if (err) throw err;
      var dbo = db.db("DataBaseName");
      dbo.collection("customers").insertOne(req.body, function(err, res) {
        if (err) throw err;
        console.log("1 document inserted");
        db.close();
      });
    });
    res.redirect("/");
});


// var _mongodb = require('mongodb');
//  var ObjectId = mongodb.ObjectId;

app.get('/delete/:id', function (req, res) {
    MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
      if (err) throw err;
      var dbo = db.db("DataBaseName");
      dbo.collection("customers").deleteOne({_id: new ObjectId(req.params.id) }, function(err, res) {
        if (err) throw err;
        // console.log({_id: req.params.id});
        console.log("1 document deleted");
        db.close();
      });
    });
res.redirect("/");
});

// Catch all other routes
app.get('*',function(req, res){
    res.send("You lost Niqqa!");
});

An entry in the database This is what it looks like in mongodb compass community.

_id:ObjectId("5c641f44923cf17c1cfe1002")
name:"Please delete me"
priority:"high"

Upvotes: 0

Views: 1371

Answers (1)

Abdelrahman Hossam
Abdelrahman Hossam

Reputation: 538

You should convert the id from the request to ObjectId as it's passed now as string which won't match the document.

const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;
const ObjectId = mongodb.ObjectId;

app.get('/delete/:id', function (req, res) {
    MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
      if (err) throw err;
      var dbo = db.db("DataBaseName");
      dbo.collection("customers").deleteOne({_id: new ObjectId(req.params.id) }, function(err, res) {
        if (err) throw err;
        console.log({_id: req.params.id});
        console.log("1 document deleted");
        db.close();
      });
    });
res.redirect("/");

You can also check the res from the delete operation to know whether any documents where deleted or not. The res should have deletedCount based on mongodb node driver docs.

Upvotes: 3

Related Questions