我试图插入多个文件到我的数据库使用node.js,事情是,我得到一个错误: MongoError:由应用程序关闭的连接 有任何选项可以并行插入多个文档?使用node.js插入多个文件到Mongodb
这里是我的代码:
var MongoClient = require('mongodb').MongoClient;
var dbName = "tst1";
var port = "27017";
var requiredCollection = "stocks"
var host = "localhost";
// open the connection the DB server
MongoClient.connect("mongodb://" + host + ":" + port + "/" + dbName, function (error, db){
console.log("Connection is opened to : " + "mongodb://" + host + ":" + port + "/" + dbName);
if(error) throw error;
var ibm = {'_id' : 1, 'value' : 1, 'ticker' : 'IBM'};
db.collection(requiredCollection).insert(ibm, function(error, inserted) {
if(error) {
console.error(error);
}
else {
console.log("Successfully inserted: " , inserted);
}
}); // end of insert
var apple = {'_id' : 2, 'vlue' : 1, 'ticker' : 'AAPL'};
db.collection(requiredCollection).insert(apple, function(error, inserted) {
if(error) {
console.error(error);
}
else {
console.log("Successfully inserted: " , inserted);
}
}); // end of insert
var intel = {'_id' : 3, 'value' : 1, 'ticker' : 'INTC'};
db.collection(requiredCollection).insert(intel, function(error, inserted) {
if(error) {
console.error(error);
}
else {
console.log("Successfully inserted: " , inserted);
}
}); // end of insert
var f5 = {'_id' : 4, 'value' : 1, 'ticker' : 'FFIV'};
db.collection(requiredCollection).insert(f5, function(error, inserted) {
if(error) {
console.error(error);
}
else {
console.log("Successfully inserted: " , inserted);
}
}); // end of insert
var arris = {'_id' : 5, 'value' : 1, 'ticker' : 'ARRS'};
db.collection(requiredCollection).insert(arris, function(error, inserted) {
if(error) {
console.error(error);
}
else {
console.log("Successfully inserted: " , inserted);
}
}); // end of insert
db.close();
}); // Connection to the DB
您需要在 “异步” 代码阅读起来。在所有其他操作完成之前调用'.close()'。操作不一定按顺序“完成”。看一下[“async”](https://github.com/caolan/async)作为节点库,以了解如何按照您的意愿在“系列”中清晰地执行此操作。一般来说,除非你真的做完了,否则你几乎从不**真的想明确关闭你的数据库连接。 – 2014-09-01 11:17:25
你能给我一些代码示例吗? – user3502786 2014-09-01 11:20:50