node.js - 使用 Node JS 连接到 Atlas MongoDB 时出错

标签 node.js mongodb mongodb-atlas

我正在尝试使用 Node js 连接到 atlas mongo db。但出现错误 TypeError: Cannot read property 'db' of null 我已在 atlas 创建了集群,并为用户 aayushg 授予了完整权限,还创建了一个数据库“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 屏幕截图 enter image description here

最佳答案

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

关于node.js - 使用 Node JS 连接到 Atlas MongoDB 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58638992/

相关文章:

javascript - 无法使用 Socket.IO 发送到 Node 服务器

node.js - Mongoose:如何在保存前手动设置_id?

javascript - 附加到 JSON 文件(Node.JS、Javascript)

node.js - Mongoose的静态方法抛出: TypeError: Model.调用没有方法 'save'

database - 通过 API 创建 MongoDB Atlas 数据库的副本

javascript - 无法从递归 javascript 函数获取值数组

javascript - 查找包含不包含特定值的数组的文档

ruby-on-rails - Mongoid:before_destroy 和 Paranoia

mongodb - 无法通过 mongo shell 连接到 mongodb atlas

javascript - 无法从 MongoDB Atlas 触发器中的集合中读取数据