Reputation: 11
I'm trying to insert data to a MongoDB database via node.js
The function addToDatabase
is invoked from a for loop
. Regardless of multiple iterations, the script don't insert data into database until its done with all iterations (at the end of for loop).
I just want the script to complete the database insert operation after each iteration.
Thanks in advance.
Here is my code:
const mongoClient = require('mongodb').MongoClient;
function addToDatabase(data){
MongoClient.connect(config.database.url, {useNewUrlParser: true}, function(err, db) {
if (err) throw err;
var dbo = db.db(config.database.dbName);
dbo.collection(config.database.collectionAd).insertOne(data, function(err, res) {
if (err) throw err;
console.log('Ad insered : ' + data._id);
db.close();
});
});
}
function getAdDetails(ads){
for (var itemKey in ads.items) {
//Statements ...
addToDatabase(obj);
}
}
getAdDetails(obj)
Upvotes: 0
Views: 256
Reputation: 1467
There're a few things not optimal in this code.
Promise.all
to wait until all inserts are donetry something like this instead
const mongoClient = require('mongodb').MongoClient
(async function () {
// connect
try {
await mongoClient.connect(config.database.url, { useNewUrlParser: true })
const db = mongoClient.db(config.database.dbName)
// do stuff
const results = await db.collection(config.database.collectionAd).insertMany(ads.items)
console.log('Ads insered : ', results)
} catch (err) {
console.log(err)
}
// close connection at the end
mongoClient.close()
})()
Upvotes: 1