【问题标题】:Error connecting to Atlas MongoDB with Node JS使用 Node JS 连接到 Atlas MongoDB 时出错
【发布时间】:2020-02-26 13:21:07
【问题描述】:

我正在尝试使用节点 js 连接到 atlas mongo db。但是收到错误TypeError: Cannot read property 'db' of null 我已经在 atlas 上创建了集群,并为用户 aayushg 提供了完整的权限,还创建了一个 db 'test'

index.js

const express = require('express')
const bodyParser= require('body-parser') 
const app = express()  
app.use(bodyParser.urlencoded({extended: true}))

const MongoClient = require('mongodb').MongoClient;

// replace the uri string with your connection string.
const url = "mongodb+srv://aayushg:<aayushg18>@cluster0-fatp8.mongodb.net/test?retryWrites=true&w=majority";

const client = new MongoClient(url, { useNewUrlParser: true });
client.connect((err, database) => {
 db = database.db("test")
 app.listen(3000, function () {
 })
  app.get('/', (req, res) => {
       //res.send('PDP')
       res.sendFile(__dirname + '/index.html')   
    })
  app.post('/quotes', (req, res) => { 
      db.collection('devices').save(req.body, (err, result) => {
         if (err) return console.log(err)
         console.log('saved to database')
         res.redirect('/')
       })
    })
})

CMD 屏幕截图

【问题讨论】:

  • 请也添加您的终端屏幕截图
  • 添加截图
  • 我认为你没有客户
  • 我也尝试过使用客户端但没有用
  • 我已经更新了我的代码

标签: node.js mongodb mongodb-atlas


【解决方案1】:

因此,错误与您在if(err) throw err 的帮助下提供的凭据有关,您可以看到错误与凭据有关。现在,您必须添加正确的凭据才能正常工作。您正在使用 &lt;aayushg18&gt; 而不是 aayushg18 谢谢。

【讨论】:

  • 错误在这一行db = database.db("test")这里database为空,连接有问题。但是您的回答表明问题在于if (err) return console.log(err),然后才抛出错误。
  • 不,我们通过聊天的凭据有错误 :)
  • 我刚刚更新了我的最后一行,让你明白,谢谢
【解决方案2】:

我有你的问题。您的连接 uri 格式不正确。输入密码时不要使用 符号。将&lt;aayushg18&gt; 替换为aayushg18,如下所示:

const uri = "mongodb+srv://aayushg:aayushg18@cluster0-fatp8.mongodb.net/test?retryWrites=true&w=majority";

【讨论】:

    猜你喜欢
    • 2020-09-27
    • 2018-09-28
    • 1970-01-01
    • 2020-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多