0

So when I run my app in deployment, with the backend connecting to MongoDB using MongoClient as follow:

import { MongoClient } from 'mongodb'

const url = process.env.MONGODB_URI 

MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true },(err, db)=>{
  console.log(url)
  db.close()
})

everything works fine. But if I change it into

import mongoose from 'mongoose'

mongoose.Promise = global.Promise
mongoose.connect(url, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true })
mongoose.connection.on('error', () => {
  throw new Error(`unable to connect to database: ${url}`)
})

it gives the following error:

webpack://HappyHourWeb/./server/server.js?:29
  throw new Error(`unable to connect to database: ${_config_config__WEBPACK_IMPORTED_MODULE_0__["default"].mongoUri}`)
   ^
Error: unable to connect to database: my_database_url,
    at NativeConnection.eval (webpack://HappyHourWeb/./server/server.js?:29:9)
    at NativeConnection.emit (node:events:390:28)
    at /Users/Hieudo/Documents/Project/HappyHourWeb/node_modules/mongoose/lib/connection.js:807:30
    at processTicksAndRejections (node:internal/process/task_queues:78:11)

Any help is greatly appreciated!

hdmicable
  • 21
  • 3
  • In your first example, you take `url` from an env var, but in your second example, url is not defined, is that intended? – Gaëtan Boyals Dec 22 '21 at 15:10
  • Does the url contain `+srv`, and if so, are you using a version of mongoose that supports it? Take a look at [Error Handling](https://mongoosejs.com/docs/connections.html#error-handling) in the mongoose docs to see how to log the specific error that occurred. – Joe Dec 22 '21 at 18:57
  • @GaëtanBoyals I am using the same url. – hdmicable Dec 22 '21 at 21:41
  • @Joe Yes my url contains +srv. It has the type below: "mongodb+srv://:@happyhour.vr5kw.mongodb.net/?retryWrites=true&w=majority". – hdmicable Dec 22 '21 at 21:45
  • Try using the equivalent `mongodb://` url. – Joe Dec 22 '21 at 22:08
  • @Joe it still does not work. I was wondering if it has anything to do with webpack. – hdmicable Dec 23 '21 at 04:10
  • I use pretty much the same code as yours with Mongoose (except I have another connection option that has nothing to do with the issue, and I use async/await syntax rather than Promises) and it works. Try logging the error that the callback gives you (add 'err' as parameter in `mongoose.connection.on('error', (err) => {`, and log it in the callback) to see the "real" error, maybe that'll be helpful. EDIT: Also, the DB connection has nothing to do with webpack – Gaëtan Boyals Dec 23 '21 at 10:29

1 Answers1

0

According to various sources, including MongoDB Connection String URI reference, Mongoose connection docs (Ctrl+F and search for srv to jump to the right topic) and the most upvoted answer on this question on SO, you should handle standard URIs and DNS URIs differently.

Mongoose accepts a dbName option that is

[...]useful if you are unable to specify a default database in the connection string like with some mongodb+srv syntax connections.

The fact that the native MongoDB driver handles it automatically doesn't necessarily means that Mongoose will. Try separating the DB name from the URI and pass it as the second argument when connecting with Mongoose.

Also, that part of your code :

mongoose.connection.on('error', () => {
  throw new Error(`unable to connect to database: ${url}`)
})

doesn't check for connection errors, it emits an event if an error is encountered after the initial connection has been made.

As Joe pointed out in the comments, you should handle both the initial connection errors AND errors that may come after it, either with the try/catch syntax or the .catch callback. More info in the docs.

Gaëtan Boyals
  • 1,193
  • 1
  • 7
  • 22