Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing documents from a mongodb collection from node.js

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!

like image 292
marc0s Avatar asked Dec 20 '13 08:12

marc0s


People also ask

Which method is used remove file in Nodejs?

unlink() method is used to remove a file or symbolic link from the filesystem.

How do I delete everything in MongoDB?

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() .


1 Answers

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();
        });
    });
});
like image 56
damphat Avatar answered Oct 05 '22 10:10

damphat