I'm deploying my express app which has mongoose connection. On localhost everything working perfectly. But when I deploy to heroku, I'm getting an error "Application error" with status 503.
When I tried to deploy without mongoose connection my application was working on heroku server perfectly. So I got that problem might be on mongoose connection.
index.js mongoose connection part of code (not working on heroku):
app.get("/", (req, res) => {
res.send(`Server launched perfectly!`);
});
const PORT = process.env.PORT || 5000;
mongoose.connect(process.env.CONNECTION_URL, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => app.listen(PORT, () => console.log(`Server Running on Port: http://localhost:${PORT}`)))
.catch((error) => console.log(`${error} did not connect`));
mongoose.connect(process.env.CONNECTION_URL).then(()=>{console.log('...')});
index.js without mongoose connection (working perfectly on heroku):
app.get("/", (req, res) => {
res.send(`Server launched perfectly!`);
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server Running on Port: http://localhost:${PORT}`));
It might be a different problem, but Procfile and package.json are fine.
CodePudding user response:
The connection should be asynchronous, you can create a function like this:
const connect = async () => {
try {
const db = await mongoose.connect(DB_URL, {
useUnifiedTopology: true,
useNewUrlParser: true,
useFindAndModify: false
});
const { name, host } = db.connection;
console.log(`Conección correcta a la base de datos ${name} en ${host}`);
} catch(error) {
console.log('Problemas al conectarse a la DB. Error ->', error);
}
};