简体   繁体   English

从node.js中删除mongodb集合中的文档

[英]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. 我是mongoDB的新手,对Node.js没有经验,所以如果下面的代码远非完美,请原谅。

The goal is to remove a document from a collection, referenced by its _id . 目标是从集合中删除文档,由_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). 删除完成(在mongo shell中检查),但代码没有结束(运行node myscript.js没有得到我的shell)。 If I add a db.close() I get { [MongoError: Connection Closed By Application] name: 'MongoError' } . 如果我添加一个db.close()我得到{ [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 你不应该使用throw for callback,throw对于函数堆栈是有益的
  • db.close() should be in the callback, after removing is done. 删除完成后, db.close()应该在回调中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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