问题描述
我是mongoDB的新手,对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.
目标是删除一个来自集合的文档,由 _id
引用。删除完成(在mongo shell中检查),但代码没有结束(运行节点myscript.js
没有得到我的shell)。如果我添加 db.close()
我得到 {[MongoError:连接应用程序关闭]名称:'MongoError'}
。
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?
谢谢!
推荐答案
欢迎使用异步样式:
- 你不应该使用throw for callback,throw对于函数堆栈是好的
-
db.close()
应该在回调中,删除完成后。
- You should not use throw for callback, throw is good for function stack
db.close()
should be in the callback, after removing is done.
示例:
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();
});
});
});
这篇关于从node.js中删除mongodb集合中的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!