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.
JavaScript
x
44
44
1
console.log("This script populates the Transaction collection so that we have some sample data for Issue #31: Uninspected Transactions Component");
2
3
let Transaction = require('./models/transaction');
4
let User = require('./models/user');
5
let mongoose = require('mongoose');
6
7
// let mongoDB = 'mongodb+srv://<username>:<password>@cluster0.dsqmg.mongodb.net/<collection-name>?retryWrites=true&w=majority';
8
mongoose.connect(mongoDB, {useNewUrlParser: true, useUnifiedTopology: true});
9
let db = mongoose.connection;
10
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
11
12
async function createTransaction(inspected, recurring, amount, note, startDateString, postDateString) {
13
14
let userQuery = await User.find({});
15
userQuery = userQuery[0];
16
17
let startDate = new Date(startDateString);
18
let postDate = new Date(postDateString);
19
20
let transaction = new Transaction({
21
user: userQuery._id,
22
inspected: inspected,
23
recurring: recurring,
24
amount: amount,
25
note: note,
26
startDate: startDate,
27
postDate: postDate
28
});
29
30
await transaction.save((err) => {
31
32
if(err){
33
console.log(err);
34
}
35
});
36
37
};
38
39
async function populateTransactions(){
40
await createTransaction(count,false, false, 563, "Numero Uno", "2012-12-05", "2012-12-06");
41
};
42
43
populateTransactions();
44
Advertisement
Answer
So I figured out that the issue was originating from
JavaScript
1
7
1
await transaction.save((err) => {
2
3
if(err){
4
console.log(err);
5
}
6
});
7
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.