1 | initial version |
The process for correctly closing a MongoDB connection and inserting data from a CSV file using node file streams can be:
const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;
const url = 'mongodb://localhost:27017/my-database';
MongoClient.connect(url, (err, client) => {
// handle errors and continue
});
const db = client.db('my-database');
const collection = db.collection('my-collection');
createReadStream()
function from the node fs
module to read the CSV file and create a stream.const fs = require('fs');
const csv = require('csv-parser');
fs.createReadStream('path/to/file.csv')
.pipe(csv())
.on('data', (data) => {
// handle data and insert into database
})
.on('end', () => {
// handle end of file and close connection
});
insertOne()
method.collection.insertOne(data, (err, result)=> {
if (err) {
// handle errors
} else {
console.log(`Inserted document with _id: ${result.insertedId}`);
}
});
close()
method.client.close();
.on('error', (err) => {
// handle errors
})