Reputation: 5659
I have a simple script to dump data into db, which I am using in conjunction of npm script. I am trying to dump data into db before my node application server starts. However the dump script doesn't complete ever and hence the server start script doesn't start. Here is my dump script -
const mongodb = require('mongodb')
, fs = require('fs')
, MongoClient = mongodb.MongoClient
, client = new MongoClient(`mongodb://localhost:27017/admin`, { useUnifiedTopology: true })
, docs = fs.readFileSync(`${process.cwd()}/app/scripts/records.json`)
client.connect().then(cl => {
const dbObj = cl.db('dumpdb')
dbObj.collection(`loc_biz_hrs`).insertMany(JSON.parse(docs)).then(result => {
console.log(`${result.insertedCount} records inserted`)
})
})
and here is how I am trying to execute it using npm script -
"scripts": {
"start": "node app/scripts/records.js && nodemon --exec babel-node index.js",
"test": "test"
}
It just displays in terminal 35755 records inserted
and gets stuck in there and doesn't execute the index.js
part of the script.
Upvotes: 1
Views: 72
Reputation: 4452
You are not closing the connection using cl.close()
, so try this:
const mongodb = require('mongodb')
, fs = require('fs')
, MongoClient = mongodb.MongoClient
, client = new MongoClient(`mongodb://localhost:27017/admin`, { useUnifiedTopology: true })
, docs = fs.readFileSync(`${process.cwd()}/app/scripts/records.json`)
client
.connect()
.then(cl => {
const dbObj = cl.db('dumpdb');
dbObj
.collection(`loc_biz_hrs`)
.insertMany(JSON.parse(docs))
.then(result => {
console.log(`${result.insertedCount} records inserted`);
cl.close();
}).catch(error => {
console.log(error);
cl.close();
})
})
.catch(error => {
console.log(error);
});
Upvotes: 1
Reputation: 11
try using concurrently npm package npm i concurrently
"scripts": {
"start": "react-scripts start",
"dev": ""concurrently \"node app/scripts/records.js\" \"nodemon --exec babel-node index.js\""
}
Upvotes: 1