Skip to content
Advertisement

Terminal hanging while running an asynchronous JS script to populate a Mongoose DB

I’m working on a personal project and am trying to understand the process logic that keeps my Node JS process from terminating after calling populateTransactions().

I think its because I need to close the DB (I’m not entirely clear on why), but when I do, the process terminates but the save() function of the model doesn’t complete and the DB isn’t written correctly.

When I let the script hang, eventually, it populates the DB correctly, but doesn’t terminate.

console.log("This script populates the Transaction collection so that we have some sample data for Issue #31: Uninspected Transactions Component");

let Transaction = require('./models/transaction');
let User = require('./models/user');
let mongoose = require('mongoose');

// let mongoDB = 'mongodb+srv://<username>:<password>@cluster0.dsqmg.mongodb.net/<collection-name>?retryWrites=true&w=majority';
mongoose.connect(mongoDB, {useNewUrlParser: true, useUnifiedTopology: true});
let db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));

async function createTransaction(inspected, recurring, amount, note, startDateString, postDateString) {

  let userQuery = await User.find({});
  userQuery = userQuery[0];

  let startDate = new Date(startDateString);
  let postDate = new Date(postDateString);

  let transaction = new Transaction({
      user: userQuery._id,
      inspected: inspected,
      recurring: recurring,
      amount: amount,
      note: note,
      startDate: startDate,
      postDate: postDate
  });

  await transaction.save((err) => {
    
    if(err){
          console.log(err);
      }
  });
  
};

async function populateTransactions(){
    await createTransaction(count,false, false, 563, "Numero Uno", "2012-12-05", "2012-12-06"); 
};

populateTransactions();

Advertisement

Answer

So I figured out that the issue was originating from

await transaction.save((err) => {
    
    if(err){
          console.log(err);
      }
  });

not following the await behavior. It turned out that the save() function doesn’t return a promise if you pass a callback as a parameter, so I refactored the code so that it didn’t use a callback and it worked as normal.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement