Can't use routes inside database async function

So, I connected to database with the following code:

const mongoose = require('mongoose');
mongoose.connect(process.env.DB, {useNewUrlParser: true, useUnifiedTopology: true});

 mongoose.connection.once("open", () => {
    //routes
  }).on("error", (error) => {
    console.log("Database connection error:", error);
  });
};

and no matter what I tried, the routes don’t work. Then, I created new, blank repl and tried the same exact thing, and this time, everything works fine.

What am I doing incorrectly?

Challenge: Issue Tracker

Link to the challenge:

It’s hard to say. Can you post a link to the repl?

Thank you

While a link to your repl.it would probably be easier for everyone, here’s what I would do since I don’t use the events.

First, something like this could be your problem. If your open event fires before that once() call executes, then its callback won’t fire (or if the event never fires, or if its name changed, …).

I never use events for this since connect() returns a promise. I typically await that promise so the code that follows is ready to go. The mongoose v5 docs state in the getting started part:

For brevity, let’s assume that all following code is within this callback.

and uses the once() listener but the rest of the docs use a mix of callbacks, promises, and async/await. But at least they warn you upfront that while mongoose can buffer db calls during connection, the rest of your code better be prepared to handle async. So I’m lazy and just await for connect() and then carry on.

here is link to repl with only this code: https://replit.com/@GregorBuar/WarmShowyCodewarrior#index.js
and here the one from fcc: https://replit.com/@GregorBuar/boilerplate-project-issuetracker#.env

Thank you for this suggestion, I’ll try and see how it goes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.