【发布时间】: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('/')
})
})
})
【问题讨论】:
-
请也添加您的终端屏幕截图
-
添加截图
-
我认为你没有客户
-
我也尝试过使用客户端但没有用
-
我已经更新了我的代码
标签: node.js mongodb mongodb-atlas