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!
unlink() method is used to remove a file or symbolic link from the filesystem.
To delete all documents that match a deletion criteria, pass a filter parameter to the deleteMany() method. The method returns a document with the status of the operation. For more information and examples, see deleteMany() .
Welcome to asynchronous style:
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();
        });
    });
});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With