I'm trying to insert multiple documents to my DB using node.js , the thing is that i'm getting an error: MongoError: Connection closed by application There is any option to insert multiple documents in parallel?
Here is my code:
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()is being called before all the other operations complete. The operations do not "complete" in order necessarily. Take a look at "async" as a node library for examples of how to clearly do this in "series" as you intend. Generally speaking though, you almost never really want to explicitly close your database connection unless you are truly done.