最近在学习使用mongodb,出现上面的错误提示。目前猜测的原因是同时进行了两次mongodb.open。 但是在mongodb.open里面已经有了mongodb.close() 进行关闭连接。为何还会这样? 下面是writter.js: var mongodb = require(’./db’); function Writter(writter) { this.name = writter.name; this.survey = writter.survey; } Writter.prototype.save = function(callback) { mongodb.open(function(err, db) { if ( err ) { mongodb.close(); return callback(err); } db.collection(“writters”, function(err, collection) { if (err) { mongodb.close(); return callback(err); } var newwritter = { name: this.name, survey: [this.survey] }; collection.ensureIndex(“name”, {unique: true}); collection.insert(newwritter, {safe: true}, function(err, writter) { mongodb.close(); callback(err); }); }); }); };
这是使用 test.js: // test writter.js var Writter = require(’./writter’); var writter = new Writter({ name:“hello”, survey: “我的第一个文档” }); writter.save(function(err) { if (err) { console.log(err); } else { console.log(“writter.save is ok”); } }); writter.save(function(err) { if (err) { console.log(err); } else { console.log(“writter.save is ok agian”); } });