繁体   English   中英

使用 Node JS 连接到 Atlas MongoDB 时出错

[英]Error connecting to Atlas MongoDB with Node JS

我正在尝试使用节点 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 的屏幕截图在此处输入图像描述

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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