1

I'm trying to save some json files inside my database using a custom function I've wrote. To achieve that I must connect to the database which I'm trying to do using this piece of code at the start of the function:

let url = "mongodb://localhost:27017/database";

(async () => {
    const directory = await fs.promises.readdir(__dirname + '/files')
    let database = await mongoose.createConnection(url, {useNewUrlParser:true, useUnifiedTopology:true});
    database.on('error', error => {
        throw console.log("Couldn't Connect To The Database");
    });
    database.once('open', function() {
        //Saving the data using Schema and save();

Weirdly enough, when executing database.once('open', function()) the callback function isn't being called at all and the program just skips the whole saving part and gets right to the end of the function.

I've searched the web for a solution, and one solution suggested to use mongoose.createConnection instant of mongoose.connect. As you can see it didn't really fixed the issue and the callback function is still not being called.

How can I fix it, and why it happens?

Thanks!

1 Answer 1

2

mongoose.createConnection creates a connection instance and allows you to manage multiple db connections as the documentation states. In your case using connect() should be sufficient (connect will create one default connection which is accessible under mongoose.connection).

By awaiting the connect-promise you don't actually need to listen for the open event, you can simply do:

...
await mongoose.connect(url, {useNewUrlParser:true, useUnifiedTopology:true});
mongoose.model('YourModel', YourModelSchema);
...
Sign up to request clarification or add additional context in comments.

4 Comments

Oh so when I use await and wait for the connect promise I don't really need to wait for the open event because await makes sure that I'm connected?
That's my understanding, yes :)
mongoose.connect doesn't return a promise
@eol Apologies. Typescript tells me "await" has no effect on the expression "mongoose.connect". Switched it to an upvote, this just didn't solve my issue

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.