简体   繁体   中英

MongoDB can be connected with MongoClient but not mongoose

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!

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM