Nivas Dhina Nivas Dhina - 3 months ago 12
Node.js Question

My document is not getting deleted in mongodb in nodejs

My document is not getting deleted from the collections. Iam also not getting any error. The http transaction is perfectly fine.

// Node Module dependencies
var express = require('express');
var router = express.Router();

// Local Module dependencies
var common = require('./common.js');
//var request = require('request');


var db =common.conn;
var Question = require('../model/questions');


router.route('/postquestion')
.post(function (req, res) {

var item = new Question(req.body);
//console.log(item);

//=======calling postdata method=====//
postQuestion(item, function (result) {

res.json(result);
});

});

router.route('/deletequestion')
.delete(function (req, res) {
console.log(req.body._id);

Question.collection.deleteOne({_id:req.body._id},function(err,question){
if(err) throw err;
console.log('the document is deleted')
res.send(question);

});

})
function postQuestion(item, fn) {
item.save(function (err) {
if (err) console.log(err);
fn(item);
});
}
module.exports = router;


postquestion function is working perfectly fine and the database is getting updated. When i use postman for raising a delete request and send the below json.

{
"_id": "57bc442c4925180b067f075b"
}


iam getting a response like the below.

{
"ok": 1,
"n": 0
}


When i check the database in robomongo i see the document is not deleted. Am i missing something to be done. Is there anything else to be done.....!

Answer

MongoDB uses ObjectID to index document.

If you want to delete object using Mongo ID you have to instanciate an ObjectID.

https://docs.mongodb.com/manual/reference/method/db.collection.deleteOne/

var ObjectID = require('mongodb').ObjectID;
router.route('/deletequestion')
    .delete(function (req, res) {
    console.log(req.body._id);
    const _id = new ObjectID(req.body._id);
    Question.collection.deleteOne({_id:_id},function(err,question){
        if(err) throw err;
        console.log('the document is deleted')
        res.send(question);

    });

})