简体   繁体   中英

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!

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();
        });
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM