[英]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('/')
})
})
})
因此,該錯誤與您在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.