17

I'm totally new to mongoDB and not experienced with Node.js so please excuse if the code below is far from perfect.

The goal is to remove a document from a collection, referenced by its _id. The removal is done (checked in mongo shell), but the code does not end (running node myscript.js doesn't get my shell back). If I add a db.close() I get { [MongoError: Connection Closed By Application] name: 'MongoError' }.

var MongoClient = require("mongodb").MongoClient;
var ObjectID = require("mongodb").ObjectID;

MongoClient.connect('mongodb://localhost/mochatests', function(err, db) {
    if (err) {
        console.log("error connecting");
        throw err;
    }
    db.collection('contacts', {}, function(err, contacts) {
        if (err) {
            console.log("error getting collection");
            throw err;
        }
        contacts.remove({_id: ObjectID("52b2f757b8116e1df2eb46ac")}, {safe: true}, function(err, result) {
            if (err) {
                console.log(err);
                throw err;
            }
            console.log(result);
        });
    });
    db.close();
});

Do I not have to close the connection? What's happening when I'm not closing it and the program doesn't end?

Thanks!

marc0s
  • 173
  • 1
  • 1
  • 5
  • 2
    Nothing happens, your program is just waiting for some I/O from Mongo driver. Of course, you know that nothing will arrive nor you won't send anything, but Node doesn't know this and thus it can't finish. – kamituel Dec 20 '13 at 09:00

1 Answers1

22

Welcome to asynchronous style:

  • You should not use throw for callback, throw is good for function stack
  • db.close() should be in the callback, after removing is done.

Example:

MongoClient.connect('mongodb://localhost/mochatests', function(err, db) {
    db.collection('contacts', {}, function(err, contacts) {
        contacts.remove({_id: ObjectID("52b2f757b8116e1df2eb46ac")}, function(err, result) {
            if (err) {
                console.log(err);
            }
            console.log(result);
            db.close();
        });
    });
});
damphat
  • 18,246
  • 8
  • 45
  • 59
  • It works but I would like to understand why you must call close so the remove actually happens... – Jeep87c Jul 19 '17 at 03:14