无法使用Express中的Mongoose连接到MongoDB Atlas

时间:2019-08-26 10:40:26

标签: express mongoose graphql

我正在尝试使用猫鼬连接到MongoDB地图集,但总是出现错误,

我尝试更改我的IP地址,也尝试更改链接 还要更改mongoDB altas中的所有设置,但总是得到相同的错误

const express = require('express')
const graphqlHTTP = require('express-graphql')
const app = express()
const catSchema = require('./Schema/categorySchema')
const mongoose = require('mongoose')

// SetUp MongoDB 
mongoose.connect('mongodb+srv://khawar111:khawar111@e-selling-bh1wv.mongodb.net/test?retryWrites=true&w=majority', { useNewUrlParser: true })
mongoose.connection.once('open', () => {
    console.log('Database Connected')
})
mongoose.connection.on('error', (e) => {
    console.log(e)
})

// Set Route for GraphQL 

app.use('/graphQL', graphqlHTTP({
    schema: catSchema,
    graphiql: true
})

)


app.listen(3000, () => {
    console.log('Server Started')
})

错误:

Error: queryTxt ETIMEOUT e-selling-bh1wv.mongodb.net
    at QueryReqWrap.onresolve [as oncomplete] (dns.js:203:19) {
  errno: 'ETIMEOUT',
  code: 'ETIMEOUT',
  syscall: 'queryTxt',
  hostname: 'e-selling-bh1wv.mongodb.net'
}
(node:25313) UnhandledPromiseRejectionWarning: Error: queryTxt ETIMEOUT e-selling-bh1wv.mongodb.net
    at QueryReqWrap.onresolve [as oncomplete] (dns.js:203:19)
(node:25313) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:25313) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

2 个答案:

答案 0 :(得分:0)

实际上,您需要从连接字符串中删除“ test?retryWrites = true&w = majority”,然后将其替换为数据库名称。

mongoose.connect('mongodb+srv://khawar111:khawar111@e-selling-bh1wv.mongodb.net/DatabaseName', { useNewUrlParser: true })

这是因为“ test?retryWrites = true&w = majority”用于测试目的

答案 1 :(得分:0)

确保将节点版本更改为2.2.12

enter image description here

并添加如下所示的IP地址:

enter image description here