Reputation: 3515
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
Upvotes: 1
Views: 10031
Reputation: 4787
In MongoDB version 3.2 and above, you can use db.collection.insertMany()
for saving multiple documents into a collection. (see documentation)
Your code can be simplified to:
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 docs = [{ _id: 1, value: 1, ticker: 'IBM' },
{ _id: 2, value: 1, ticker: 'AAPL' },
{ _id: 3, value: 1, ticker: 'INTC' },
{ _id: 4, value: 1, ticker: 'FFIV' },
{ _id: 5, value: 1, ticker: 'ARRS' }];
db.collection(requiredCollection).insertMany(docs, function(error, inserted) {
if(error) {
console.error(error);
}
else {
console.log("Successfully inserted: " , inserted );
}
}); // end of insert
db.close();
}); // Connection to the DB
Upvotes: 5
Reputation: 1
you could use mongo bulk insert https://docs.mongodb.com/manual/reference/method/Bulk.insert/
var bulk = db.items.initializeUnorderedBulkOp();
bulk.insert( { item: "abc123", defaultQty: 100, status: "A", points: 100 } );
bulk.insert( { item: "ijk123", defaultQty: 200, status: "A", points: 200 } );
bulk.insert( { item: "mop123", defaultQty: 0, status: "P", points: 0 } );
bulk.execute();
Upvotes: 0
Reputation: 151190
The "async" library helps you here as you need to understand "callbacks" in asynchronous code and the main thing this helps you with is "code creep" by removing the need to "indent" each "next" call in code.
In fact you can do these in "parallel" rather than "series" for a reasonable amount of operations. We just need to "wait" for each to complete, which is what a "callback" is for. It "calls back" to invoke the "next action" when the operation is complete:
var MongoClient = require('mongodb').MongoClient,
async = require('async');
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;
async.parallel(
[
function(callback) {
var ibm = {'_id' : 1, 'value' : 1, 'ticker' : 'IBM'};
db.collection(requiredCollection).insert(ibm, function(error, inserted) {
if(error) {
console.error(error);
callback(error);
} else {
console.log("Successfully inserted: " , inserted );
callback();
}
}); // end of insert
},
function(callback) {
var apple = {'_id' : 2, 'vlue' : 1, 'ticker' : 'AAPL'};
db.collection(requiredCollection).insert(apple, function(error, inserted) {
if(error) {
console.error(error);
callback(error);
} else {
console.log("Successfully inserted: " , inserted );
callback();
}
}); // end of insert
},
function(callback) {
var intel = {'_id' : 3, 'value' : 1, 'ticker' : 'INTC'};
db.collection(requiredCollection).insert(intel, function(error, inserted) {
if(error) {
console.error(error)
callback(error);
} else {
console.log("Successfully inserted: " , inserted );
callback();
}
}); // end of insert
},
function(callback) {
var f5 = {'_id' : 4, 'value' : 1, 'ticker' : 'FFIV'};
db.collection(requiredCollection).insert(f5, function(error, inserted) {
if(error) {
console.error(error);
callback(error);
} else {
console.log("Successfully inserted: " , inserted );
callback();
}
}); // end of insert
},
function(callback) {
var arris = {'_id' : 5, 'value' : 1, 'ticker' : 'ARRS'};
db.collection(requiredCollection).insert(arris, function(error, inserted) {
if(error) {
console.error(error)
callback(error);
} else {
console.log("Successfully inserted: " , inserted );
}
}); // end of insert
},
],
function(err) {
// called when everything is done
db.close();
}
);
}); // Connection to the DB
Each operation now waits for it's "callback" to be called from it's own "callback" context as well as there being the "flow control" to wait until all operations have completed before finally "closing" the connection at the end of all operations.
But as said earlier, unless this is a "one off" script you basically never call .close()
on the database connection and you only ever open it once.
Upvotes: 1