使用 Node JS 连接到 Atlas MongoDB 时出错
Error connecting to Atlas MongoDB with Node JS
我正在尝试使用节点 js 连接到 atlas mongo 数据库。但是出现错误 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 屏幕截图
因此,错误与您在 if(err) throw err
的帮助下提供的凭据有关,您可以看到错误与凭据有关。现在,您必须添加正确的凭据才能正常工作。您正在使用 <aayushg18>
而不是 aayushg18
谢谢。
我知道你的问题了。您的连接 uri 格式不正确。输入密码时不要使用<>符号。将 <aayushg18>
替换为 aayushg18
,如下所示:
const uri = "mongodb+srv://aayushg:aayushg18@cluster0-fatp8.mongodb.net/test?retryWrites=true&w=majority";
我正在尝试使用节点 js 连接到 atlas mongo 数据库。但是出现错误 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 屏幕截图
因此,错误与您在 if(err) throw err
的帮助下提供的凭据有关,您可以看到错误与凭据有关。现在,您必须添加正确的凭据才能正常工作。您正在使用 <aayushg18>
而不是 aayushg18
谢谢。
我知道你的问题了。您的连接 uri 格式不正确。输入密码时不要使用<>符号。将 <aayushg18>
替换为 aayushg18
,如下所示:
const uri = "mongodb+srv://aayushg:aayushg18@cluster0-fatp8.mongodb.net/test?retryWrites=true&w=majority";