0

I am new to Node.

I have a script that makes a bunch of async calls, writes the results to a database, then is supposed to finish. However, when the logic finishes executing, the script just sits there and does not exit. I have to ^c or explicitly close the mongoose connection. If I do, it exits.

What is the efficient way to determine that all the results are saved and close the connection? Is there not a way to automatically close when all the the connections are finished? Do I need to keep track of them all myself?

Even if I do, it still blows up on a larger number of tasks. So obviously they were not all done.

With synchronous programming it's easy. Open at the start and close at the end. But with async, there are forks all over the place. How can I know that everything has finished? Do you track all the connections in a datastructure? Do you rely on a connection timeout? There must be an efficient way to do it.

Thanks

PrecisionPete
  • 3,139
  • 5
  • 33
  • 52
  • Maybe this is your solution https://stackoverflow.com/questions/8813838/properly-close-mongooses-connection-once-youre-done – DaCurse Jul 24 '19 at 01:11
  • Sam problem unfortunately... (node:20122) UnhandledPromiseRejectionWarning: MongoError: server instance pool was destroyed – PrecisionPete Jul 24 '19 at 12:49

1 Answers1

0

This will help.

const mongoose = require('mongoose')
const Schema = mongoose.Schema
mongoose.connect("mongodb://localhost/stack-overflow", { useNewUrlParser: true })

var userSchema = new Schema({
    username:  {
        type: String,
        required: true,
        unique: true,
        trim: true,
        minlength: 3
    },
  },
  {
    timestamps: true
  });

const User = mongoose.model('User', userSchema);

// This part below is the answer
async function run() {
    try {
        const result = await User.find({})
        console.log(result)
        exitMe();
    } catch(error) {
        console.log(error)
    }
} 

function exitMe() {
    mongoose.connection.close()
    process.exit();
}

run()
Prasanta Bose
  • 674
  • 5
  • 13