Removing documents from a mongodb collection from node.js

前端 未结 1 1158
执念已碎
执念已碎 2021-01-04 01:36

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 collecti

1条回答
  •  情歌与酒
    2021-01-04 01:54

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

    0 讨论(0)
提交回复
热议问题